2016-09-16 2 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 

Database

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' condition.Check сейчас. – Vicky

Смежные вопросы