SQLite PRAGMA table_info(表)不返回列名(在C#中使用Data.SQLite)

Ben*_*Ben 0 c# sqlite

我使用以下示例代码,并希望以某种方式获取sqlite3数据库的列名称:

using System;
using System.Data.SQLite;
namespace Program
{
class Program
{
    static void Main(string[] args)
    {
        Program stuff = new Program();
        stuff.DoStuff();
        Console.Read();
    }
    private void DoStuff()
    {
        SQLiteConnection.CreateFile("Database.sqlite");
        SQLiteConnection con = new SQLiteConnection("Data Source=Database.sqlite;Version=3;");
        con.Open();
        string sql = "create table 'member' ('account_id' text not null unique, 'account_name' text not null);";
        SQLiteCommand command = new SQLiteCommand(sql, con);
        command.ExecuteNonQuery();
        sql = "insert into member ('account_id', 'account_name') values ('0', '1');";
        command = new SQLiteCommand(sql, con);
        sql = "PRAGMA table_info('member');";
        command = new SQLiteCommand(sql, con);
        SQLiteDataReader reader = command.ExecuteReader();
        while (reader.Read())
        {
            Console.WriteLine(reader.GetName(0));
        }
        con.Close();
    }

}
}
Run Code Online (Sandbox Code Playgroud)

我也试过了

for(int i=0;i<reader.FieldCount;i++)
{
   Console.WriteLine(reader.GetName(i));
}

var columns = Enumerable.Range(0, reader.FieldCount).Select(reader.GetName).ToList();
Run Code Online (Sandbox Code Playgroud)

我得到的唯一结果是以下输出:"cid name type notnull dflt_value pk"虽然我没有得到实际的列名.我确实需要列名,因为我正在根据结果向数据库写新列来自我无法访问的其他服务器的API.打印数据时,我想确保显示正确的列名.

Ben*_*Ben 7

我真的认为 SQLite 讨厌我 - 所以而不是查询 beeing

PRAGMA table_info('member');
Run Code Online (Sandbox Code Playgroud)

我现在用

SELECT * FROM member WHERE 1 = 2;
Run Code Online (Sandbox Code Playgroud)

这当然只会返回表格本身而没有任何内容。但是 - reader.GetName(i) 实际上是返回真实的列名!我只花了 5 个小时试图让 'PRAGMA table_info('table_name')' 工作来解决这个问题......


CL.*_*CL. 5

所述PRAGMA table_info语句返回数据等的查询,即,有一个固定的列数,并且在每个列中的值的行数.每行中的数据对应于您询问的表格的一列:

sqlite> pragma table_info(member);
cid      name          type     notnull  dflt_value  pk     
-------  ------------  -------  -------  ----------  -------
0        account_id    text     1                    0      
1        account_name  text     1                    0      

调用GetName()返回列名称.调用GetString()等返回行值:

while (reader.Read()) {
    Console.WriteLine("field name: " + reader.GetString(1));
}
Run Code Online (Sandbox Code Playgroud)