2015-11-02 7 views
0

Я получаю сообщение об ошибке синтаксиса в инструкции UPDATE всякий раз, когда я пытаюсь обновить информацию в моей базе данных Access. Я пробовал перемещать вещи и добавлять запятые или отнимать запятые. Я застрял, какие-то предложения относительно того, что я могу сделать? Ошибка прикреплена ко второму cmd.ExecuteNonQuery(); внизу.Ошибка синтаксиса в инструкции UPDATE VS 2015

if (txtdateId.Text != "") 
{ 
    if (txtdateId.IsEnabled == true) 
    { 
     cmd.CommandText = 
       "insert into tbEmp(DateofService, AssociateName, DeviceType, DeviceModel, Serial, Issue, Part1, Part2, Part3, RepairedBy, Campus) Values('" + 
       txtdateId.Text + "','" + txtEmpName.Text + "','" + txtContact.Text + "','" + txttype.Text + 
       "','" + txtserial.Text + "','" + txtAddress.Text + "','" + txtpart1.Text + "','" + txtpart2.Text + 
       "','" + txtpart3.Text + "','" + txtrepaired.Text + "','" + txtcampus.Text + "')"; 
     cmd.ExecuteNonQuery(); 
     BindGrid(); 
     MessageBox.Show("Device Added Successfully"); 
     ClearAll(); 
    } 
    else 
    { 
     cmd.CommandText = "update tbEmp set DateofService = ,'" + txtdateId.Text + ",AssociateName = '" + txtEmpName.Text + ",DeviceType = '" + txtContact.Text + ",DeviceModel = '" + txttype.Text + ",Serial = '" + txtserial.Text + ",Issue = '" + txtAddress.Text + ",Part1 = '" + txtpart1.Text + ",Part2 = '" + txtpart2.Text + ",Part3 = '" + txtpart3.Text + ",RepairedBy = '" + txtrepaired.Text + "where Campus = '" + txtcampus.Text; 
     cmd.ExecuteNonQuery(); 
     BindGrid(); 
     MessageBox.Show("Device updated"); 
     ClearAll(); 
    } 
} 
+3

[SQL Injection предупреждение] (http://msdn.microsoft.com/en-us/library/ms161953%28v=sql.105%29.aspx) - вы должны ** не ** сцепить вместе ваши SQL-операторы - используйте ** параметризованные запросы **, чтобы избежать SQL-инъекции. –

ответ

1

Вы пропустили несколько ' в вас заявлении также у вас есть один дополнительный ' после DateofService. Ваше заявление должно быть так:

cmd.CommandText = "update tbEmp set DateofService = '" + txtdateId.Text + "',AssociateName = '" + txtEmpName.Text + "' , ... 

Кроме того, я настоятельно рекомендую вам использовать parameterized queries, чтобы избежать SQL Injection так:

В SQL:

cmd.CommandText = "update tbEmp set DateofService = @txtdateId ,..."; 
cmd.Parameters.AddWithValue("txtdateId",txtdateId.Text); 

И для доступа и OleDB:

cmd.CommandText = "update tbEmp set DateofService = ? , ...."; 
cmd.Parameters.AddWithValue("DateofService ",txtdateId.Text); 

Хотя конкретно укажите тип и используйте Va lue свойство лучше, чем AddWithValue. Проверьте это: Can we stop using AddWithValue() already?

+1

Фактически, MS Access и OleDB не поддерживают ** именованные ** параметры, такие как '@ txtdateId' - Access использует только параметры'? 'и * positional * –

0

Это решение вашей проблемы, но я предпочел бы, чтобы вы добавили подтверждение для SQL-инъекции. Сначала возьмите значение текстового поля, чтобы подтвердить его, затем передайте запрос.

cmd.CommandText = "update tbEmp set DateofService = '" + txtdateId.Text + "' ,AssociateName = '" + txtEmpName.Text + "' ,DeviceType = '" + txtContact.Text + "',DeviceModel = '" + txttype.Text + "',Serial = '" + txtserial.Text + "',Issue = '" + txtAddress.Text + "',Part1 = '" + txtpart1.Text + "',Part2 = '" + txtpart2.Text + "' ,Part3 = '" + txtpart3.Text + "' ,RepairedBy = '" + txtrepaired.Text + "' where Campus = '" + txtcampus.Text + "'"; 
+0

Это все еще не хватает некоторых закрывающих одинарных кавычек. – juharr

+0

@juharr, спасибо. Я только что обновил – Jigneshk

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