c#中T-SQL语句中的语法不正确

时间:2016-02-11 18:49:53

标签: c# sql sql-server database

我有以下代码:

USE [DB] INSERT INTO Extract2_EventLog VALUES (" + li.userId + ", '" + li.startTime.ToString() + "', '" + li.endTime.ToString() + "', '" + li.elapsedTime.ToString() + (li.actionType == ActionType.REPORT ? "', 'report')" : "', 'extract')', '" + status + "'");

当我运行它时,我收到以下错误:

  

{“''附近的语法不正确,'。\ r \ n \ n \ n之后的闭合引号   字符串''。“}

我看不出我做错了什么..任何人?

4 个答案:

答案 0 :(得分:3)

男人......从哪里开始...

首先,您应该使用接受参数的存储过程(来自应用程序代码的变量)。其次,应用程序中应该有一个dataaccess层,用于分隔数据库调用和用户界面。我无法强调这是多么重要以及你当前的方法有多糟糕。在你纠正之前,你将永远与这样的问题作斗争。

但要解决问题,因为它被问到...你的错误是因为你的查询字符串格式不正确。使用调试工具在将字符串发送到数据库之前查看该字符串,然后您应该能够快速确定它的错误。要进行故障排除,您始终可以将该字符串剪切并粘贴到SSMS中,在其中进行优化,然后对您的c#代码进行必要的更改。

答案 1 :(得分:2)

首先看看Stan Shaw的答案,接下来看看Jon Skeet的评论!

  

要做的第一件事是立即停止构建SQL ......使用参数化的SQL,您可能会发现问题就消失了......而且您将同时阻止SQL注入攻击。

他们说了一切重要的事情,只是为了给你一个直接的回答:

您的代码中有status + "'");,需要更改为status + "')"; ...

...喜欢这个:

string statement = "USE [DB] INSERT INTO Extract2_EventLog VALUES (" + li.userId + ", '" + li.startTime.ToString() + "', '" + li.endTime.ToString() + "', '" + li.elapsedTime.ToString() + (li.actionType == ActionType.REPORT ? "', 'report')" : "', 'extract')', '" + status + "')";

答案 2 :(得分:2)

不应将值连接到查询中,而应使用参数化查询或存储过程。

重写代码可能类似于(取决于数据类型等):

string commandText = "INSERT INTO Extract2_EventLog (userId, startTime, endTime, elapsedTime, actionType, [status]) VALUES (@userId, @startTime, @endTime, @elapsedTime, @actionType, @status)";

using (SqlConnection connection = new SqlConnection(connectionString))
{
    SqlCommand command = new SqlCommand(commandText, connection);
    command.Parameters.AddWithValue("@userId", li.userId);
    command.Parameters.AddWithValue("@startTime", li.startTime);
    command.Parameters.AddWithValue("@endTime", li.endTime);
    command.Parameters.AddWithValue("@elapsedTime", li.elapsedTime);
    command.Parameters.AddWithValue("@actionType", li.actionType == ActionType.REPORT ? "report" : "extract");
    command.Parameters.AddWithValue("@status", status);

    connection.Open();
    int rowsAffected = command.ExecuteNonQuery();
    Console.WriteLine("RowsAffected: {0}", rowsAffected);
}

答案 3 :(得分:0)

你忘记了“开头。所以你的代码用非sql恢复sql。 你的例子似乎不完整。