这是我的代码,但它给我一个执行过程中遇到的 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;
}
还有一些事情;
- 尽可能不要使用
AddWithValue
。 It may generate unexpected and surprising results sometimes .使用Add
方法重载来指定您的参数类型及其大小。 - 使用
using
statement自动处理您的数据适配器。
顺便说一句,你的方法中没有没有 cmd
。在您的方法中定义您的命令和连接,同时使用 using
语句处理它们。
关于c# - 如何像查询一样参数化mysql?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35547841/