【问题标题】:Selecting data from a table on button click单击按钮从表中选择数据
【发布时间】:2017-04-03 20:18:18
【问题描述】:

我正在尝试将一个表提取到DataGridView,但它显示一个空表。

private void button1_Click(object sender, EventArgs e)
{
    var dt = new DataTable();

    var SDA = new SqlDataAdapter("Select * from "+txt_Search.Text+" ", conn);

    SDA.Fill(dt);
    dgv.DataSource = dt;
    txt_Search.Text = "";
}

【问题讨论】:

  • 首先要做的是在你的代码中放置一个断点,并在你将它分配为数据源时检查 dt 中是否有任何数据。
  • @ChrisBerger -- 不首先要做的就是掩护,因为 sql 注入攻击将是灾难性的。
  • 很难说这里出了什么问题。首先,确保您没有忽略A first chance of XXXXException...。并测试每一步:conn是否打开成功?表名是保留关键字吗?(可能想用 [] 或 `` 引用)该表是否包含数据? ...等
  • @Hogan - 好吧,你说得有道理。我假设唯一会在 txt_Search 中输入的人是程序员,因为它看起来就像有人在尝试学习如何编码。但重要的是要指出,您永远不应该在查询字符串中包含用户提供的文本。通常你会使用参数化查询,但当然你不能用表名来做。如果 OP 真的想要这样做,他们会想要验证它是一个有效的表名。 (而且可能只是不应该这样做。)
  • 一旦解决了,你需要考虑SQL injection。由于恶意用户可能会尝试搜索类似 `random_table;删除表重要表”。

标签: c# sql datagridview


【解决方案1】:

您提供的代码 sn-p 没有提供太多上下文。请尝试使用我提供的以下 sn-p。也许你看到了你错过的东西。希望这会有所帮助。

const string connectionString = "";
SqlConnection connection = new SqlConnection(connectionString)

public DataTable ExecuteCommandToDataTable(string commandText, CommandType 
commandType, int timeout, params SqlParameter[] parameters)
{
    if (this.connection == null)
        throw new NullReferenceException("The connection was not initialized.");

    SqlCommand command = new SqlCommand(commandText, 
    this.connection.SqlConnection);            
    command.CommandType = commandType;
    command.CommandTimeout = timeout;

    for (int i = 0; parameters != null && i < parameters.Length; i++)
        command.Parameters.Add(parameters[i]);


    this.connection.Open();

    DataTable tbl = new DataTable();
    using (SqlDataAdapter adapter = new SqlDataAdapter(sqlCommand))
    {
        adapter.Fill(tbl);
    }

    this.connection.Close();

    return tbl;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-20
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-24
    • 2019-06-15
    相关资源
    最近更新 更多