我正在c#
构建一个sql
查询来执行登录,最后我得到一个语法错误,但我无法弄清楚导致错误的原因
SqlDataAdapter sda = new SqlDataAdapter("Select * From bruker Where Brukernavn='"
+ Textbox1.Text + "' and Passord='" + TextBox2.Text"");
缺少
"+"
,需要将连接字符串或SqlConnection
作为第二个参数传递
SqlDataAdapter sda = new SqlDataAdapter("Select * From bruker Where Brukernavn='" + Textbox1.Text + "' and Passord='" + TextBox2.Text +"","connectionString");
或
SqlDataAdapter sda = new SqlDataAdapter("Select * From bruker Where Brukernavn='" + Textbox1.Text + "' and Passord='" + TextBox2.Text +"",con);
由于上面的代码容易受到 sql 注入的影响,请使用下面的代码来防止 sql 注入。
try
{
SqlConnection con = new SqlConnection("connectionString");
SqlCommand commnad = new SqlCommand("Select * From bruker Where Brukernavn=@username and Passord=@password", con);
commnad.Parameters.AddWithValue("@username", Textbox1.Text.Trim);
commnad.Parameters.AddWithValue("@password", Textbox2.Text.Trim);
//rest of the code
}
catch(Exception ex)
{
//log exception and re-throw or send a generic exception message to UI
throw;
}
finally
{
//close the connection
}
如果可以解决您的问题,请将其标记为答案。