2016-09-16 101 views
-1

我嘗試用此代碼更新我的MYSQL表。MySQL查詢不起作用(C#)

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

什麼錯查詢?

感謝您的幫助!

+0

後這裏你在運行時的'sqlquery'得到。 – feeeper

+1

你的列名是'1'? –

+0

當代碼啓動@ feeeper時出現錯誤 – Eugene

回答

2

你爲什麼不這樣做的更優雅的方式:喜歡的東西:

using (SqlConnection connection = new SqlConnection(connectionString)) 
using (SqlCommand command = connection.CreateCommand()) 
{ 
command.CommandText = "if exists(select 1 from orders where id [email protected])  
begin 
update orders set customer_id = @customer_id, total = @total, fio = @fio, adress [email protected] 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(); 
} 
+0

在整潔性方面好得多 – vish1990

+0

有同樣的錯誤 – Eugene

+0

錯過'if'條件中的閉括號。立即檢查。 – Vicky