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

本文关键字:是否 存在 记录 错误 检查 SQL | 更新日期: 2023-09-27 18:02:34

我使用这段代码来检查值(guid1)是否已经存在于'guid'表中:

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)

但是在

 strResult = (String)myCommand.ExecuteScalar();

行,得到sqlException错误

'guid'附近语法不正确

请告诉我这里有什么问题?

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

"SELECT guid" + "FROM trafficScotland" + "WHERE guid ="

:

SELECT guidFROM trafficScotlandWHERE guid =

无论如何,把它分解成单独的字符串是没有意义的,但是你缺少了单词之间的空格:)

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();
}

^^这是一个改进版本。请允许我提出几点批评:

  • 您的查询没有使用参数:只是构建一个字符串。安全性、可读性和可维护性风险
  • 假设你正在检查是否有一个带有该guid的条目,建议可能没有,但你没有检查DBNull.Value,以防没有
  • 只是有点混乱-你返回一个string,但处理Guid s。奇怪。

不如这样做:

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...
}

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

注意guid后面有空格

每个人都告诉你问题是什么。是的,你的问题不正确。但是你未来的问题呢?你想怎么看他们说的对不对?

我强烈建议您使用SQL Server Profiler。分析器位于应用程序和数据库引擎之间,并掌握传递给数据库引擎的每个命令和查询。因此,您可以看到传递给SQL Server的内容,获取它,并尝试在SQL Server Management Studio中执行它以调试它。

理想情况下,您应该使用参数来防止SQL注入。它们还将处理诸如引用需要引用的值(如guid)之类的事情:

var selectString =  "SELECT guid FROM trafficScotland WHERE guid = @guid";
var myCommand = new SqlCommand(selectString, myConnection);
myCommand.Parameters.AddWithValue("@guid", guid1);
strResult = (String)myCommand.ExecuteScalar();

首先你必须修复你的间距,你是连接查询的一部分在一起,你错过了重要的sql server关键字之间的空间。

SELECT guidFROM trafficScotlandWHERE guidid

其次,应该使用命名参数。这将有助于避免sql注入,这将防止你不得不考虑是否需要单引号在你的sql变量。

var query = "SELECT guid FROM trafficScotland WHERE guid = @guid";
using(var command = new SqlCommand(query, connection))
{
    command.Parameters.AddWithValue("@guid", guid1);
    var result = command.ExecuteScalar();
    // Compare guid1 to result
}

正如所写的那样,由于您忘记了一些空格,因此您正在运行以下查询

SELECT guidFROM trafficScotlandWHERE guid = {guid here}

try this:

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

空格+像其他人提到的那样用"'"括起来。您还应该将GUIDs存储为UNIQUEIDENTIFIERs(假设MSSQL)