【问题标题】:Is it possible to get column name (header) in SQLite using C#?是否可以使用 C# 在 SQLite 中获取列名(标题)?
【发布时间】:2013-06-21 12:29:00
【问题描述】:

如果表和列是在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();
}

【问题讨论】:

  • 警告:您的代码容易受到SQL Injection 攻击。要清楚,您想要行和列的名称吗?看起来这不是您在上面的代码中检索的内容。
  • @Brian 是的,我只想获取每个生成表的所有列名。
  • 数据库访问代码(当然在后面的代码中),后跟MessageBox,然后是txtUsername.Focus();。史诗。请老兄,获取一些关于编程的介绍教程。您的代码几乎违反了人类创造的每一个良好实践和模式。
  • 我只是从网上获取这段代码只是想展示我想要做什么。 :)

标签: c# wpf sqlite


【解决方案1】:

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

【讨论】:

  • 这只会想到一个列名。他都想要。
  • @Brian:好吧,我想我可以展示如何编写一个 for 循环。哈哈。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2015-06-16
    • 1970-01-01
    • 1970-01-01
    • 2018-06-22
    • 2017-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多