c# - 如何像查询一样参数化mysql?

标签 c# mysql winforms parameters sql-like

这是我的代码,但它给我一个执行过程中遇到的 fatal error

private void recregtxt_TextChanged(object sender, EventArgs e)
{
        if (recregcmb.Text == "Student ID")
        {
            MySqlDataAdapter sda = new MySqlDataAdapter("select StudID, LastName, FirstName, MiddleInitial, Address, Age, Birthday, Gender, Guardian, ContactNumber as 'Contact Number', Year as 'Year Level' from registeredTBL where StudID LIKE @key", conn);
            DataTable data = new DataTable();
            sda.Fill(data);
            dataGridView2.DataSource = data;

            cmd.Parameters.AddWithValue("@key", recregtxt.Text + "%");
        }
}

谁能帮我解决这个问题。

最佳答案

因为您尝试在使用数据适配器执行它之后 添加您的参数名称和它的值。您应该在执行它之前添加 if

if (recregcmb.Text == "Student ID")
{
    MySqlDataAdapter sda = new MySqlDataAdapter("select StudID, LastName, FirstName, MiddleInitial, Address, Age, Birthday, Gender, Guardian, ContactNumber as 'Contact Number', Year as 'Year Level' from registeredTBL where StudID LIKE @key", conn);
    cmd.Parameters.AddWithValue("@key", recregtxt.Text + "%");
    DataTable data = new DataTable();
    sda.Fill(data);
    dataGridView2.DataSource = data;
}

还有一些事情;

顺便说一句,你的方法中没有没有 cmd。在您的方法中定义您的命令和连接,同时使用 using 语句处理它们。

关于c# - 如何像查询一样参数化mysql?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35547841/

相关文章:

c# - 我可以通过附近的多边形查询带有边界多边形的 DocumentDB 文档吗?

c# - 将命令行参数传递给我的应用程序的已运行实例

c# - 在新 TAB 中打开链接(WebBrowser 控件)

c# - 抑制 GUID 警告作为 mt.exe 生成后事件的结果

c# - 如何远程访问自托管的 Nancy 服务?

python - Flask 中的 If 语句使用 SQL 数据库中的字符串变量

mysql - 1条sql语句中的多重计数

sql - MySQL 中的 NULL(性能和存储)

c# - 检测外部进程的窗口是否闪烁

c# - 列表在调试时不填充,直到打开