[英]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.