如何修复System.Data.SqlClient.SqlException:'附近的语法不正确。

时间:2019-04-22 07:19:00

标签: c# asp.net

im在前端使用asp.net和c#创建网站。我有两个表,我正在尝试使用以下查询更新一个表的列。但是即时通讯收到以下错误。谁能帮我解决这个问题。

string sql = "UPDATE CurrentStudent SET CurrentStudent.DateOfJoining ='" + dateOfJoining.Text + "',CurrentStudent.DateOfLeaving = '" + dateOfLeaving.Text + "',CurrentStudent.Course = '"+ "'FROM CurrentStudent SI INNER JOIN UserDetails UI ON SI.Email = UI.Email'"+"'";


System.Data.SqlClient.SqlException
  HResult=0x80131904
  Message=Incorrect syntax near ''.
  Source=.Net SqlClient Data Provider
  StackTrace:
<Cannot evaluate the exception stack trace>

2 个答案:

答案 0 :(得分:3)

您丢失了From和可能的字符串结尾之间的空格:

"UPDATE CurrentStudent SET CurrentStudent.DateOfJoining ='" + dateOfJoining.Text + "',CurrentStudent.DateOfLeaving = '" + dateOfLeaving.Text + "',CurrentStudent.Course = '"+ Course.Text +"' FROM CurrentStudent SI INNER JOIN UserDetails UI ON SI.Email = UI.Email'"+"'"

注意“'FROM添加的空间。

尝试上面的字符串,我也建议您使用参数化查询。一些有用的链接:

link1

link2

关于为何使用参数化查询的更多信息:

SQL Injection

why use parameterized queries

答案 1 :(得分:2)

实际的问题是使用字符串连接。即使固定了多余的引号或空格,也总是可以输入无效的字符串,与服务器的语言环境不匹配的日期(例如22.04.2019)或导致SQL注入的实际恶意字符串。

使用带有强类型参数的参数化查询实际上更容易,然后使用字符串连接:

var sql = @"UPDATE CurrentStudent 
SET CurrentStudent.DateOfJoining =@joinDate
    CurrentStudent.DateOfLeaving = @leaveDate,
    CurrentStudent.Course = ''
FROM CurrentStudent SI INNER JOIN UserDetails UI ON SI.Email = UI.Email";

using(var conn=new SqlConnection(...))
using(var cmd=new SqlCommand(sql,conn);
{
    var joinDate=cmd.Parameters.Add("@joinDate",SqlDbType.Date);
    var leaveDate=cmd.Parameters.Add("@leaveDate",SqlDbType.Date);

    //Set a DateTime, not a string
    joinDate.Value=joinDaterPicker.Value;
    leaveDate.Value=leaveDatePicker.Value;

    conn.Open();
    cmd.ExecuteNonScalar();
}

您可以使用Dapper之类的microORM来进一步简化代码:

var sql = @"UPDATE CurrentStudent 
SET CurrentStudent.DateOfJoining =@joinDate
    CurrentStudent.DateOfLeaving = @leaveDate,
    CurrentStudent.Course = ''
FROM CurrentStudent SI INNER JOIN UserDetails UI ON SI.Email = UI.Email";

using(var conn=new SqlConnection(...))
{
    conn.Execute(sql,new { joinDate  = joinDaterPicker.Value, 
                           leaveDate = leaveDatePicker.Value});
}