在更新查询中获取语法错误

时间:2013-06-17 10:29:52

标签: c# sql .net database

我收到语法错误。

  

在chareter字符串'OKWhere之后的未闭合的quatation标记   UerName =山姆。 'OKWhere UserName = sam'附近的IncorrectSysntax。

代码:

cmd.CommandText = "UPDATE SystemInfo SET" + " UserName='" + UserName + "',
UserDomainName='" + UserDomainName + "',UserMachineName='" + UserMachineName 
+"',UserIP='" + UserIP + "', UserOsVersion='" + UserOsVersion + 
"',UserSystemDirectory='" + UserSystemDirectory + "',UserCurrentDirectory='" + 
UserCurrentDirectory + "', ProcessorName='" + ProcessorName + "', 
ProcessMnufacturer='" + ProcessMnufacturer + "',ProcessorID='" + ProcessorID + 
"',ProcessorDescription='" + ProcessorDescription + "',ProcessorVersion='" + 
ProcessorVersion + "',ProcessorStatus='" + ProcessorStatus + "',ProcessorDeviceId='" + 
ProcessorDeviceId + "', OSCaption='" + OSCaption + "',OSSerialNumber='" +  
SSerialNumber + "',OSManufacturer ='" + OSManufacturer + "',OSVersion='" + OSVersion + 
"', OSStatus='" + OSStatus + "',OSName='" + OSName + "', BiosName='" + BiosName + 
"',BiosVersion='" + BiosVersion + "',BiosSerialNumber='" + BiosSerialNumber + "', 
BiosManufacturer='" + BiosManufacturer + "',BiosCurrentlanguage='" + 
BiosCurrentlanguage + "', BiosStatus='" + BiosStatus + "Where UserName=" + 
UserName.ToString ();

3 个答案:

答案 0 :(得分:6)

BiosStatus + "Where UserName="

WHERE子句之前需要一个空格并在UserName附近添加引号,它应该如下所示:

BiosStatus + " Where UserName='" + UserName.ToString() + "'"

作为附加说明,请尝试使用paramerterized queries。这样可以防止SQL Injection次攻击。您可以通过执行以下操作来实现此目的:

command.CommandText = "UPDATE TABLE " +  
         "SET BiosStatus = $BiosStatus, BiosManufacturer = $BiosManufacturer " +  
         "WHERE UserName = $UserName";  

 command.Parameters.AddWithValue("$BiosStatus", BiosStatus);  
 command.Parameters.AddWithValue("$BioManufacturer", BiosManufacturer);  
 command.Parameters.AddWithValue("$UserName", UserName);  

答案 1 :(得分:1)

参数。始终是参数。实际上,由于所有输入似乎都是当前实例(this)的属性,因此像" dapper"可以真的帮助你:

conn.Execute(@"UPDATE SystemInfo SET
UserName=@UserName,
UserDomainName=@UserDomainName,
UserMachineName=@UserMachineName,
UserIP=@UserIP,
-- ...lots skipped...
BiosCurrentlanguage=@BiosCurrentlanguage,
BiosStatus=@BiosStatus
Where UserName=@UserName", this);

this作为第二个参数使用SQL 中存在的当前实例的所有属性来添加参数,因此它将添加@UserName,{ {1}}等等......

您当然可以使用原始ADO.NET手动执行相同操作 - 这只需要做更多工作:

@UserDomainName

答案 2 :(得分:-2)

尝试纠正

表格

BiosStatus + "Where UserName="

BiosStatus + " Where UserName='"+  UserName.ToString ()+ "'";