从 SQL table 中选择但抛出异常

Selecting from a SQL table but there is an exception thrown

当我想阅读 table:

时出现此错误

System.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near ','. at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() at System.Data.SqlClient.SqlDataReader.get_MetaData() at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds, Boolean describeParameterEncryptionRequest) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) at System.Data.SqlClient.SqlCommand.ExecuteReader() at hamsohbat.Form1.showFriends(Update update) in C:\Users\Soroush\documents\visual studio 2015\Projects\hamsohbat\hamsohbat\Form1.cs:line 327 at hamsohbat.Form1.GetUpdates(Int64 ii, Int32 offset) in C:\Users\Soroush\documents\visual studio 2015\Projects\hamsohbat\hamsohbat\Form1.cs:line 113 ClientConnectionId:02ad4c40-e0e7-47ac-91cc-ad88bcdf057d Error Number:102,State:1,Class:15

我的代码的相关部分是:

        using (SqlConnection con = new SqlConnection(@"Data Source=.\sqlexpress;AttachDbFilename=" + Directory.GetCurrentDirectory() + @"\MembersDB.mdf;Integrated Security=True;User Instance=True"))
        {
            foreach (Int32 x in matches)
            {
                con.Open();
                using (SqlCommand cmd = new SqlCommand("SELECT ([UserName], [FName], [LName], [NickName]) FROM [Table] WHERE [TelegramId]=" + x.ToString(), con))

                    using (SqlDataReader reader = cmd.ExecuteReader())

                        while (reader.Read())

                            bot.SendTextMessage(update.Message.Chat.Id, "Nick: " + reader["NickName"].ToString() + "\nFirst Name: " + reader["FName"].ToString() + "\nLast Name: " + reader["LName"].ToString() + "\nTelegram ID: @" + reader["UserName"].ToString());

            }

        }

我在我的代码行之间放置了一些发送消息来跟踪它,我认为问题出在这一行上(也许我错了):

using (SqlCommand cmd = new SqlCommand("SELECT ([UserName], [FName], [LName], [NickName]) FROM [Table] WHERE [TelegramId]=" + x.ToString(), con))

我的 table 的列是 Id、TelegramId、Username、FName、LName、Nickname

感谢您的关注

您只需删除 SELECT 查询中的“(”和“)”。希望对你有用。

using (SqlCommand cmd = new SqlCommand("SELECT [UserName], [FName], [LName], [NickName] FROM [Table] WHERE [TelegramId]=" + x.ToString(), con))

您不必在列名的开头和结尾放置大括号 ( ),这可能是您的查询出现语法错误的原因,您应该先尝试 运行在 sql 服务器中查询,如果运行正常,则将其移植到代码库中,通过删除不必要的大括号来更改查询:

SELECT [UserName], [FName], [LName], [NickName] FROM [Table]

并且您不应该按照正确的方式在查询中进行字符串连接,您需要使用参数化查询来避免 SQL 注入攻击。

要了解如何编写参数化查询,请参考以下内容post:

Parameterize SQL query

或这个 link 也有帮助:

http://csharp-station.com/Tutorial/AdoDotNet/Lesson06

希望对您有所帮助。

您在 select 语句中使用括号似乎有问题:

SELECT ([UserName], [FName], [LName], [NickName]) FROM [Table] WHERE [TelegramId]=1

应该是:

SELECT [UserName], [FName], [LName], [NickName] FROM [Table] WHERE [TelegramId]=1

(在 [用户名] 之前和 [昵称] 之后没有括号)。

有了括号,数据库将尝试将括号内的术语解释为单个术语,因此会抱怨意外的逗号。

是的 我删除了大括号并且它起作用了。谢谢朋友们

我将该行代码更改为:

using (SqlCommand cmd = new SqlCommand("SELECT ([UserName], [FName], [LName], [NickName]) FROM [Table] WHERE [TelegramId]=" + x.ToString(), con))

成功了

更改此行

using (SqlCommand cmd = new SqlCommand("SELECT ([UserName], [FName], [LName], [NickName]) FROM [Table] WHERE [TelegramId]=" + x.ToString(), con))

进入这个

using (SqlCommand cmd = new SqlCommand("SELECT [UserName], [FName], [LName], [NickName] FROM [Table] WHERE [TelegramId]=" + x.ToString(), con))