如何通过PRAGMA(.net / c#)从sqlite中的表中获取列名?

时间:2013-07-18 07:57:57

标签: c# .net sqlite

我一直在努力获得正确的c#代码,以便在PRAGMA table_info查询后获取值。

由于我在this post中拒绝使用额外代码进行编辑,因此我向其他人提出了这个问题,否则会浪费数小时来快速解决问题。

3 个答案:

答案 0 :(得分:13)

假设您想要一张DataTable表格字段列表:

 using (var con = new SQLiteConnection(preparedConnectionString))
    {
       using (var cmd = new SQLiteCommand("PRAGMA table_info(" + tableName + ");"))
        {
            var table = new DataTable();

            cmd.Connection = con;
            cmd.Connection.Open();

             SQLiteDataAdapter adp = null;
                try
                {
                    adp = new SQLiteDataAdapter(cmd);
                    adp.Fill(table);
                    con.Close();
                    return table;
                }
              catch (Exception ex)
              { }
         }
     }

返回结果是:

  • cid:列的ID
  • name:列的名称
  • type:列的类型
  • notnull:如果列可以包含空值,则为0或1
  • dflt_value:默认值
  • pk:0或1,如果列与主键部分

如果您只希望将列名添加到List中,则可以使用(您必须包含System.Data.DataSetExtension):

 return table.AsEnumerable().Select(r=>r["name"].ToString()).ToList();

编辑:或者您可以使用此代码避免DataSetExtension引用:

using (var con = new SQLiteConnection(preparedConnectionString))
      {
          using (var cmd = new SQLiteCommand("PRAGMA table_info(" + tableName + ");"))
          {
              var table = new DataTable();
              cmd.Connection = con;
              cmd.Connection.Open();

              SQLiteDataAdapter adp = null;
              try
              {
                  adp = new SQLiteDataAdapter(cmd);
                  adp.Fill(table);
                  con.Close();
                  var res = new List<string>();
                  for(int i = 0;i<table.Rows.Count;i++)
                      res.Add(table.Rows[i]["name"].ToString());
                  return res;
              }
              catch (Exception ex){ }
          }
      }
      return new List<string>();

您可以在SQLite中使用很多PRAGMA语句,查看链接。

关于using声明:它非常简单,用于确保一次性对象将被丢弃在您的代码中发生的任何事情:请参阅this linkthis reference

答案 1 :(得分:1)

代码

DB = new SQLiteConnection(@"Data Source="+DBFileName);
DB.Open();
SQLiteCommand command = new SQLiteCommand("PRAGMA table_info('tracks')", DB);
DataTable dataTable = new DataTable();
SQLiteDataAdapter dataAdapter = new SQLiteDataAdapter(command);
dataAdapter.Fill(dataTable);
DB.Close();
foreach (DataRow row in dataTable.Rows) { 
    DBColumnNames.Add((string)row[dataTable.Columns[1]]); }  
            //Out(String.Join(",", 
    DBColumnNames.ToArray()));//debug

结果行中的所有元素
int cid, string name, string type,int notnull, string dflt_value, int pk

有关PRAGMA

的更多信息

答案 2 :(得分:-1)

不确定这是否正是您所追求的,但这就是我抓取数据并随后使用它的方式。希望能帮助到你! 显然,转换并未涵盖所有可能性,只是我到目前为止所需要的。

    /// <summary>
    ///  Allows the programmer to easily update rows in the DB.
    /// </summary>
    /// <param name="tableName">The table to update.</param>
    /// <param name="data">A dictionary containing Column names and their new values.</param>
    /// <param name="where">The where clause for the update statement.</param>
    /// <returns>A boolean true or false to signify success or failure.</returns>
    public bool Update(String tableName, Dictionary<String, String> data, String where)
    {
        String vals = "";
        Boolean returnCode = true;

        //Need to determine the dataype of fields to update as this affects the way the sql needs to be formatted
        String colQuery = "PRAGMA table_info(" + tableName + ")";
        DataTable colDataTypes = GetDataTable(colQuery);


        if (data.Count >= 1)
        {

            foreach (KeyValuePair<String, String> pair in data)
            {

                DataRow[] colDataTypeRow = colDataTypes.Select("name = '" + pair.Key.ToString() + "'");

                String colDataType="";
                if (pair.Key.ToString()== "rowid" || pair.Key.ToString()== "_rowid_" || pair.Key.ToString()=="oid")
                {
                    colDataType = "INT";
                }
                else
                {
                    colDataType = colDataTypeRow[0]["type"].ToString();

                }
                colDataType = colDataType.Split(' ').FirstOrDefault();
                if ( colDataType == "VARCHAR")
                {
                    colDataType = "VARCHAR";
                }

                switch(colDataType)
                {
                    case "INTEGER": case "INT": case "NUMERIC": case "REAL":
                            vals += String.Format(" {0} = {1},", pair.Key.ToString(), pair.Value.ToString());
                            break;
                    case "TEXT": case "VARCHAR": case "DATE": case "DATETIME":
                            vals += String.Format(" {0} = '{1}',", pair.Key.ToString(), pair.Value.ToString());
                            break;

                }
            }
            vals = vals.Substring(0, vals.Length - 1);
        }
        try
        {
            string sql = String.Format("update {0} set {1} where {2};", tableName, vals, where);
            //dbl.AppendLine(sql);
            dbl.AppendLine(sql);
            this.ExecuteNonQuery(sql);
        }
        catch(Exception crap)
        {
            OutCrap(crap);
            returnCode = false;
        }
        return returnCode;
    }