SQLite - 将表的列名存储在字符串列表中

时间:2014-01-20 11:02:57

标签: c# sql sqlite datagridview

我不知道如何将SQLite表中的列名存储到字符串列表中。 以下代码使用列名称(以及其他内容)填充dataGridView:

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

2 个答案:

答案 0 :(得分:1)

如果您希望将查询绑定到列表而不是DataGridView,那么您应该使用数据 reader 而不是数据 set ,例如

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

答案 1 :(得分: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();
            }