是否可以使用C#在SQLite中获取列名(头)

本文关键字:获取 可以使 SQLite 是否 | 更新日期: 2023-09-27 18:19:40

如果表和列是在sqlite中以code'behind生成的,那么是否可以获取列名(Header)?

尝试过,但失败了:

SQLiteCommand cmd = new SQLiteCommand();
string sSQL = "Select * from tblUser Where username = '" + txtUsername.Text + "'";
cmd.CommandText = sSQL;
cmd.Connection = clsCon.con;
SQLiteDataReader dr2;
dr2 = cmd.ExecuteReader();
string columnName = dr2.GetName(1);
dr2.Read();
if (dr2.HasRows)
{
    MessageBox.Show("Username Already Exist!", "SQLite Test Application", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
    txtUsername.Focus();
}

是否可以使用C#在SQLite中获取列名(头)

1)确保数据库打开

2) 确保命令与连接连接

3) 确保你没有得到任何错误

4) 循环浏览列名

var cmd = new SQLiteCommand("select * from t1", db);
var dr = cmd.ExecuteReader();
for (var i = 0; i < dr.FieldCount; i++)
{
    Console.WriteLine(dr.GetName(i));
}

根据muratgu提供的答案,我创建了以下方法:

/// <summary>
/// Checks if the given table contains a column with the given name.
/// </summary>
/// <param name="tableName">The table in this database to check.</param>
/// <param name="columnName">The column in the given table to look for.</param>
/// <param name="connection">The SQLiteConnection for this database.</param>
/// <returns>True if the given table contains a column with the given name.</returns>
public static bool ColumnExists(string tableName, string columnName, SQLiteConnection connection)
{
    var cmd = new SQLiteCommand($"PRAGMA table_info({tableName})", connection);
    var dr = cmd.ExecuteReader();
    while (dr.Read())//loop through the various columns and their info
    {
        var value = dr.GetValue(1);//column 1 from the result contains the column names
        if (columnName.Equals(value))
        {
            dr.Close();
            return true;
        }
    }
    dr.Close();
    return false;
}
相关文章: