MySQL查询不起作用(C#)

时间:2016-09-16 06:41:30

标签: c# mysql mysql-connector mysqlconnection

我尝试使用此代码更新我的MYSQL表。

string sqlquery = String.Format("if exists(select 1 from orders where id =\" {0}\" ) begin update orders set customer_id = \"{1}\", total = \"{2}\", fio = \"{3}\", adress =\" {4}\" where id = \"{0}\" end else begin insert into orders (id, customer_id, total, fio, adress) values(\"{0}\", \"{1}\", \"{2}\", \"{3}\", \"{4}\") end", id, customer_id, total, fio, adress);

MySqlCommand addCommand2 = new MySqlCommand(sqlquery.ToString(), connection);
addCommand2.ExecuteNonQuery();

但我有这个错误

Additional information: 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 'if exists(select 1 from orders where id = 1913 ) begin update orders set custome' at line 1

数据库

enter image description here

查询有什么问题?

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

为什么不以更优雅的方式做到这一点:像。:

using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = connection.CreateCommand())
 { 
command.CommandText = "if exists(select 1 from orders where id =@id)    
 begin 
 update orders set customer_id = @customer_id, total = @total, fio = @fio, adress =@adress where id = @id end 
 else
  begin insert into orders (id, customer_id, total, fio, adress) values(@id, @customer_id, @total, @fio,@adress) end";

   command.Parameters.AddWithValue("@id", val1);
   command.Parameters.AddWithValue("@customer_id", val2);
   command.Parameters.AddWithValue("@total", val3);
   command.Parameters.AddWithValue("@fio", val4);
    command.Parameters.AddWithValue("@adress", val5);
   connection.Open();
   command.ExecuteNonQuery();
   connection.Close();
 }