如何在C#和T-SQL代码中解决此错误

时间:2019-05-01 15:53:18

标签: c# sql sql-server sqlconnection

我用SQL查询填充数据表,但出现此错误:

  

System.Data.SqlClient.SqlException:''='附近的语法不正确。

这是我的代码:

SqlConnection sqlConnection = new SqlConnection("Data Source=OWNER;Initial Catalog=train-database;Integrated Security=True;Pooling=False");
SqlDataAdapter sda = new SqlDataAdapter("SELECT c_id FROM [user] WHERE E_mail = '"+ f3.E_Mail3.Text +"' and password = "+f3.Password3.Text+" ", sqlConnection);

DataTable dt = new DataTable();
sda.Fill(dt);

1 个答案:

答案 0 :(得分:0)

密码值必须与用户名部分一样用单引号引起来

SqlConnection sqlConnection = new SqlConnection("Data Source=OWNER;Initial Catalog=train-database;Integrated Security=True;Pooling=False");
    SqlDataAdapter sda = new SqlDataAdapter("select c_id From [user] Where E_mail = '"+ f3.E_Mail3.Text +"' and password = '"+f3.Password3.Text+"' ", sqlConnection); 
    DataTable dt = new DataTable(); 
    sda.Fill(dt);

但是此代码容易受到SQL注入攻击的侵害,使用字符串连接创建SQL查询确实是一个坏习惯。

强烈建议使用SQL参数。

以下代码不是完整的工作代码,因为我离我的想法很近,但我相信您可以解决它。

SqlConnection sqlConnection = new SqlConnection("Data Source=OWNER;Initial Catalog=train-database;Integrated Security=True;Pooling=False");

SqlCommand command= new SqlCommand("select c_id from [users] where e_mail =@emailparam and password =@passwordparam",sqlConnection);
command.Parameters.Add(new SqlParameter("emailparam",f3.Email.text));
command.Parameters.Add(new SqlParameter("passwordparam", f3.password.text));

SqlDataAdapter sda = new SqlDataAdapter(command); 
DataTable dt = new DataTable(); sda.Fill(dt);