【问题标题】:SQLite - storing the column names of a table in a list of stringsSQLite - 将表的列名存储在字符串列表中
【发布时间】:2014-01-20 11:02:57
【问题描述】:

我不知道如何将 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();
}

【问题讨论】:

  • datagrid中添加的表名正常吗?
  • 在数据网格中,我正确获取了列名(数据网格中的第一列称为名称,每行是我表中列的名称。数据网格中的第二列称为 cid,第三种类型,第四个 not_null 等)。

标签: c# sql sqlite datagridview


【解决方案1】:

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

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

【讨论】:

  • 谢谢詹姆斯。您对使用数据阅读器是正确的。我尝试使用它,但我不知道语法。我刚开始使用 C#。我必须做一个小改动 - tableNames.Add(Convert.ToString(reader["name"]))
  • @Nick_F 啊是啊忘了它返回object 而不是字符串,或者你可以调用reader.GetString(0) 其中0 是列号或reader["name"].ToString() 但是后者意味着它会失败,如果namenull
【解决方案2】:
            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();
            }

【讨论】:

  • 感谢迪特里希的帮助。我选择了 James 提出的解决方案,因为他先发布了它并且对我有用。
  • 没问题^-^我们是来寻求帮助的。
  • @DietrichPrg 你可以用更少的代码做到这一点,var names = dtb.Rows.Select(x =&gt; x.Item["name"]);。我选择了SQLiteDataReader,因为我假设OP不需要DataSet。但是,如果 OP 已经在使用 DataSet 这将是更有效的选择。
  • @James 我知道这一点,但我有一些使用 DataReader 的经验,我认为,这个组件有问题,需要保持与服务器的连接,对我来说,这是一个问题,因为您与远离您的服务器一起工作,并且您没有良好的互联网链接,这在巴西很难拥有,该组件花费的时间比将所有内容都存储在 DataTable 中并使用它花费的时间更多。
  • @DietrichPrg 这不是一个问题,而是一个实现细节。两者都是有目的的,你不应该盲目地说一个比另一个更好,这真的取决于情况。 this answer 中的 2 之间的区别有一个很好的类比。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-18
  • 2021-09-24
  • 2017-12-29
  • 1970-01-01
  • 2022-07-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多