这是我的c#代码中应该在特定按钮上执行的方法:
private void button2_Click(object sender, EventArgs e)
{
try
{
string connectionString = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True";
SqlConnection con = new SqlConnection(connectionString);
con.Open();
string query = "SELECT Code, Description, Next_Code FROM Liguanea_Lane2 WHERE code LIKE '%" + search.Text + "%'; ";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
string scode = dr.GetString(dr.GetOrdinal("next_code"));
textBox2.Text = scode;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
//next description
try
{
string connectionString1 = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True";
SqlConnection con1 = new SqlConnection(connectionString1);
con1.Open();
string query1 = "SELECT Code, Description, Next_Description FROM Liguanea_Lane2 WHERE code LIKE '%" + search.Text + "%'; ";
SqlCommand cmd1 = new SqlCommand(query1, con1);
SqlDataReader dr1 = cmd1.ExecuteReader();
while (dr1.Read())
{
string sdes = dr1.GetString(dr1.GetOrdinal("Next_Description"));
textBox3.Text = sdes;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
search.ResetText();
textBox1.Clear();
search.SelectedIndex = search.SelectedIndex + 1;
textBox2.Clear();
textBox3.Clear();
string connectionString2 = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True";
SqlConnection con2 = new SqlConnection(connectionString2);
con2.Open();
string query2 = "UPDATE Liguanea_Lane2 SET Update_val= '0' where code = '" + search.Text + "'; ";
}
}
其中的特定区块提出了问题:
string connectionString2 = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True";
SqlConnection con2 = new SqlConnection(connectionString2);
con2.Open();
string query2 = "UPDATE Liguanea_Lane2 SET Update_val= '0' where code = '" + search.Text + "'; ";
要添加更多洞察力,它的功能是插入我的MSSQL数据库表中名为“update_val”的列。根据名为“search”的comboBox的输入插入此值。我在MSSQL中运行查询,它的工作原理。唯一的区别是,不是从comboBox接收,而是使用“WHERE”命令指定值。 c#中的问题是它根本不更新MSSQL中的表。所以我在问我的语法是否错误。
PS。是的我知道应该实现参数化查询以避免SQL注入。这只是我自己的做法。因此,没有任何评论,因为它与此相关。
答案 0 :(得分:2)
要执行更新命令,您需要执行更多类似的操作:
using (SqlConnection connection = new SqlConnection(
connectionstring1)) // You won't need a second connection string if both are the same
{
SqlCommand command = new SqlCommand(query2, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}