![](/img/trans.png)
[英]Fix the exception System.Data.SqlClient.SqlException: 'Incorrect syntax near '='.'
[英]How to fix System.Data.SqlClient.SqlException: 'Incorrect syntax near ''.'
即时通讯使用c#在前端使用asp.net创建一个网站。 我有两个表,我正在尝试使用以下查询更新一个表的列。 但是即时通讯收到以下错误。 谁能帮我解决这个问题。
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>
实际的问题是使用字符串连接。 即使固定了多余的引号或缺少的空格,也始终可以输入无效的字符串,与服务器的语言环境不匹配的日期(例如, 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});
}
您错过了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添加的空间。
尝试上面的字符串,我也建议您使用参数化查询。 一些有用的链接:
还有更多关于为什么使用参数化查询的信息:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.