简体   繁体   English

C# MySQL 插入

[英]C# MySQL Insert

The following C# code is producing an "SQL Syntax Error..."以下 C# 代码产生了“SQL 语法错误...”

string query = "INSERT INTO jobscollection (number,desc,client,jobtype,statustype,initials) VALUES(@number,@desc,@client,@jobtype,@statustype,@initials)";

MySqlCommand cmd = new MySqlCommand( query, connection );

cmd.Parameters.Add( "@number", MySqlDbType.VarChar ).Value = JobNumber;
cmd.Parameters.Add( "@desc", MySqlDbType.VarChar ).Value = Description;
cmd.Parameters.Add( "@client", MySqlDbType.Int32 ).Value = clientId;
cmd.Parameters.Add( "@jobtype", MySqlDbType.Int32 ).Value = typeID;
cmd.Parameters.Add( "@statustype", MySqlDbType.Int32 ).Value = statusId;
cmd.Parameters.Add( "@initials", MySqlDbType.VarChar ).Value = Initials;

cmd.ExecuteNonQuery();

Link below is an image of the table in MySQL workbench.下面的链接是 MySQL 工作台中表格的图像。 Also the clientID, jobtype and status types are foreign key to IDs in other tables (and the IDs do exist)此外,clientID、jobtype 和 status 类型是其他表中 ID 的外键(并且 ID 确实存在)

MySQL Table MySQL表

Can anyone spot my error?谁能发现我的错误?

Here is the full exception message这是完整的异常消息

{MySql.Data.MySqlClient.MySqlException (0x80004005): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc,client,jobtype,statustype,initials) VALUES('1007.01','Test',3,2,3,'PI')' at line 1    
at MySql.Data.MySqlClient.MySqlStream.ReadPacket()
at MySql.Data.MySqlClient.NativeDriver.GetResult(Int32& affectedRow, Int64& insertedId)
at MySql.Data.MySqlClient.Driver.GetResult(Int32 statementId, Int32& affectedRows, Int64& insertedId)
at MySql.Data.MySqlClient.Driver.NextResult(Int32 statementId, Boolean force)
at MySql.Data.MySqlClient.MySqlDataReader.NextResult()
at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader()
at MySql.Data.MySqlClient.MySqlCommand.ExecuteNonQuery()
at PCE.DatabaseUtility.InsertNewJob(String JobNumber, String Description, Int32 clientId, Int32 typeID, Int32 statusId, String Initials)}

And the connection string和连接字符串

string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";"
+ "Allow User Variables=true;";

DESC is a reserved (My)SQL keyword . DESC是保留的(My)SQL 关键字

You'll need to either rename your column or escape it in the query, like this:您需要重命名列或在查询中将其转义,如下所示:

INSERT INTO jobscollection (number,`desc`,client,jobtype,statustype,initials) VALUES(@number,@desc,@client,@jobtype,@statustype,@initials)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM