C#检查SQL错误中是否存在记录

Dan*_*ell 5 .net c# sql

我正在使用此代码来检查'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)

^^这是一个改进版本.如果我可以批评几点:

  • 没有参数用于您的查询:只需构建一个字符串.安全性,可读性和可维护性风险
  • 大概你正在检查是否有与GUID的项,这表明有可能不是,但你不检查DBNull.Value,以防有不
  • 只是有点混乱 - 你回来了,string但处理Guids.奇.


Yuc*_*uck 6

做这样的事情:

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)


hun*_*ind 2

selectString = "SELECT guid " + "FROM trafficScotland" + " WHERE guid = '" + guid1 +"'";

注意引导后的空格

  • -1 同样,您永远不应该以这种方式将参数传递给查询。只是没有充分的理由 (3认同)
  • 这样很容易出现SQL注入。我更喜欢其他答案中提出的带有参数的解决方案。 (2认同)