2016-10-03 490 views
0

我用下面的示例代码,并希望得到一个sqlite3的数据库列名以某种方式:的SQLite PRAGMA table_info(表)不返回列名(在C#中使用Data.SQLite)

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(); 
    } 

} 
} 

我也试过

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

var columns = Enumerable.Range(0, reader.FieldCount).Select(reader.GetName).ToList(); 

唯一的结果我得到的是下面的输出: “CID名类型NotNull dflt_value PK” 我不虽然得到实际的列名.. 我需要的列名,因为我给t写新的专栏他的数据库取决于来自另一个服务器的API的结果,我无法访问它。在打印数据时,我想确保显示正确的列名称。

+0

我使用System.Data.SQLite 1.0.103(以防万一你想知道) – Ben

回答

1

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)); 
} 
+0

只是为了请确保:我希望结果是'account_id'和'account_name'的东西 - 如屏幕截图所示 - 我没有得到这些值作为回报..- http://puu.sh/rwfiZ/4166090e28.png – Ben

+0

添加更好的截图:http://puu.sh/rwfth/8a86ba9bd9.png – Ben

0

我真的觉得SQLite的恨我 - 所以不是查询beeing

PRAGMA table_info('member'); 

我现在用

SELECT * FROM member WHERE 1 = 2; 

本课程只会将桌子本身没有任何内容地归还给我。 但是 - reader.GetName(i)实际上是返回真正的列名称!只花了我5小时试图让'PRAGMA table_info('table_name')'的工作,以弄清楚...