wpf 是否可以使用 C# 在 SQLite 中获取列名(标题)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17284967/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 09:04:13  来源:igfitidea点击:

Is it possible to get column name (header) in SQLite using C#?

c#wpfsqlite

提问by Jesson

Is it possible to get column names(Header) if table and columns are generated code'behind in sqlite?

如果表和列是在 sqlite 中生成的代码“隐藏”,是否可以获取列名(标题)?

tried this but it fail:

试过这个,但失败了:

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

回答by muratgu

1) make sure the db is open

1)确保数据库是打开的

2) make sure the command is hooked up with the connection

2)确保命令与连接挂钩

3) make sure you are not getting any errors

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

4) loop through the column names

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

回答by Peet

Based on the answer provided by muratguI created the following method:

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