2016-10-03 31 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')'的工作,以弄清楚...

相關問題