2014-01-20 87 views
0

我不知道如何将SQLite表中的列名存储到字符串列表中。 下面的代码填充与列名一个DataGridView(除其他事项外):SQLite - 将表名的列名存储在字符串列表中

string sDatabasePath = DBPath(); 
SQLiteConnectionStringBuilder datasource = new SQLiteConnectionStringBuilder(); 
datasource.Add("Data Source", sDatabasePath); 
datasource.Add("Version", "3"); 
datasource.Add("New", "False"); 
datasource.Add("Compress", "True");    
using (SQLiteConnection connection = new SQLiteConnection(datasource.ConnectionString)) 
{ 
    connection.Open(); //opens connection 
    SQLiteCommand getColumnNames = new SQLiteCommand("PRAGMA table_info('myTable');", connection); 
    SQLiteDataAdapter myAdapter = new SQLiteDataAdapter(getColumnNames); 
    DataSet myDataSet = new DataSet(); 
    //myAdapter.Fill(myDataSet, "name"); 
    this.dataGridView1.DataSource = myDataSet; 
    this.dataGridView1.DataMember = "name"; 
    connection.Close(); 
} 
+0

的表名通常在数据网格添加? –

+0

在datagrid中,我正确地获取了列名(datagrid中的第一列称为name,每行都是我表中列的名称,datagrid中的第二列称为cid,第三类,第四个not_null等)。 –

回答

1

如果您想查询绑定到一个列表,而不是一个DataGridView,那么你应该使用一个数据读者和不是数据set eg

using (SQLiteConnection connection = new SQLiteConnection(datasource.ConnectionString)) 
using (SQLiteCommand cmd = new SQLiteCommand("PRAGMA table_info('myTable');")) 
{ 
    connection.Open(); //opens connection 
    var tableNames = new List<string>(); 
    using (SQLiteDataReader reader = cmd.ExecuteReader()) 
    { 
     while (reader.Read()) 
     { 
      tableNames.Add(reader.GetString(0)); // read 'name' column 
     } 
    } 
    return tableNames; 
} 
+0

谢谢詹姆斯。你对使用数据阅读器是正确的。我尝试过使用它,但我不知道语法。我刚开始使用C#。有一个小的变化,我不得不做的 - tableNames.Add(Convert.ToString(reader [“name”])) –

+0

@Nick_F啊是啊忘了它返回'对象',而不是字符串,或者你可以调用'reader.GetString( 0)'其中'0'是列号或'reader [“name”]。ToString()'但是后者意味着如果'name'为'null'则失败。 – James

1
  DataTable dtb = new DataTable(); 
      myAdapter.Fill(dtb); 

      string[] names = new string[dtb.Rows.Count]; 
      for (int i = 0; i < dtb.Rows.Count; i++) 
      { 
       DataRow row = dtb.Rows[i]; 
       names[i] = row[0].ToString(); 
      } 
+0

谢谢迪特里希的帮助。我采用了James提出的解决方案,因为他首先发布了它,并为我工作。 –

+0

没问题^ - ^我们在这里尝试帮助。 –

+0

@DietrichPrg你可以用更少的代码来做到这一点,var names = dtb.Rows.Select(x => x.Item [“name”]);'。我去了'SQLiteDataReader',因为我在OP的假设下不需要'DataSet'。但是,如果OP已经使用'DataSet',这将是更有效的选择。 – James

相关问题