C# 在c中添加数据库列的值#
我想在c#中添加数据库列的值,并将其保存在变量中。请帮我向前走。提前谢谢 我想:这是可能的C# 在c中添加数据库列的值#,c#,C#,我想在c#中添加数据库列的值,并将其保存在变量中。请帮我向前走。提前谢谢 我想:这是可能的 SqlCommand myCommand3 = new SqlCommand("select sum(credit_hour) from [student_reg] WHERE [std_id]= '" + id + "' ", myConnection); 是的,这是可能的 问题1:不需要将整数参数括在单引号内 解决方案1: SqlCommand myCommand3 = new SqlCommand
SqlCommand myCommand3 = new SqlCommand("select sum(credit_hour) from [student_reg] WHERE [std_id]= '" + id + "' ", myConnection);
是的,这是可能的
问题1:不需要将整数参数括在单引号内
解决方案1:
SqlCommand myCommand3 = new SqlCommand("select sum(credit_hour) from
[student_reg] WHERE [std_id]= " + id, myConnection);
建议:您的查询容易受到SQL注入攻击,我建议您使用参数化查询来避免这些攻击
解决方案2:使用参数化查询
试试这个
SqlCommand myCommand3 = new SqlCommand("select sum(credit_hour) from [student_reg] WHERE [std_id]= @Id ", myConnection);
myCommand3.Parameters.AddWithValue("@Id", id);
con.Open();
int sum = (int) myCommand3.ExecuteScalar();
是否要将credit_hour之和添加到变量?这取决于列类型。
SqlCommand myCommand3 = new SqlCommand("select sum(credit_hour) from [student_reg] WHERE [std_id]= @Id ", myConnection);
myCommand3.Parameters.AddWithValue("@Id", id);
con.Open();
int sum = (int) myCommand3.ExecuteScalar();