我正在使用此代码来检查'guid'表中是否已存在值(guid1):
string selectString = "SELECT guid" + "FROM trafficScotland" + "WHERE guid = " + guid1;
SqlCommand myCommand = new SqlCommand(selectString, myConnection);
String strResult = String.Empty;
strResult = (String)myCommand.ExecuteScalar();
if (strResult.Length == 0)
Run Code Online (Sandbox Code Playgroud)
但在
strResult = (String)myCommand.ExecuteScalar();
Run Code Online (Sandbox Code Playgroud)
一行,我得到sqlException错误
'guid'附近的Incorrent语法
请告诉我这里有什么问题?
Kie*_*one 12
"SELECT guid" + "FROM trafficScotland" + "WHERE guid ="
Run Code Online (Sandbox Code Playgroud)
那是:
SELECT guidFROM trafficScotlandWHERE guid =
Run Code Online (Sandbox Code Playgroud)
无论如何将它分解为单独的字符串是没有意义的,但是你在字之间缺少空格:)
string resultGuidAsString = null;
// build command object
string cmdQuery = "SELECT guid FROM trafficScotland WHERE guid=@guid";
SqlCommand myCmd = new SqlCommand(cmdQuery, myConnection);
// safely pass in GUID parameter value
myCmd.Parameters.AddWithValue("@guid", guid1);
// read result, check for nulls in DB
object result = myCmd.ExecuteScalar();
if (result != DBNull.Value && result != null)
{
resultGuidAsString = result.ToString();
}
Run Code Online (Sandbox Code Playgroud)
^^这是一个改进版本.如果我可以批评几点:
DBNull.Value,以防有不string但处理Guids.奇.做这样的事情:
var selectString = "SELECT 1 FROM trafficScotland WHERE guid = @guid"
var myCommand = new SqlCommand(selectString, myConnection);
myCommand.Parameters.AddWithValue("@guid", guid1);
var itExists = (Int32)myCommand.ExecuteScalar() > 0;
if (itExists) {
// do stuff...
}
Run Code Online (Sandbox Code Playgroud)
selectString = "SELECT guid " + "FROM trafficScotland" + " WHERE guid = '" + guid1 +"'";
注意引导后的空格
| 归档时间: |
|
| 查看次数: |
12140 次 |
| 最近记录: |