System data oledb oledbexception ошибка синтаксиса в инструкции update

I have been getting a syntax error in my UPDATE datagridview code which happens to work in another .cs file. My group has been looking at different solutions online but everything won’t work.

My group has been looking at different solutions online but everything won’t seem to work.

        {
            connection.Open();
            OleDbCommand cmd = connection.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "Update Table1 set treatment = '" + treat.Text + "', remarks = '" + appRemarks.Text + "', cost = '" + treatCost.Text + "', Time = '" + textBox2.Text + "' where lastName = '" + Lastname.Text + "' ";


            cmd.ExecuteNonQuery();
            connection.Close();
            MessageBox.Show("Updated Successfully!");
        }

The expected output should be Updated Successfully! and it should reflect in the database file after clicking the update button. Sometimes the output is «Microsoft Engine database» which does not save the changes.

The error says «System.Data.OleDb.OleDbException: ‘Syntax error in UPDATE statement.'» pointing to cmd.ExecuteNonQuery();

asked May 28, 2019 at 16:58

Dzeija's user avatar

6

First, never use string concatenation to build a query. You’re asking for a SQL Injection attack. The biggest thing I could see here is make sure that only columns that are string columns (varchar, char, text, etc..) have single-quoted values. Is cost a number? If so then it should be:

, cost=" + treatCost.Text + ", 

If cost is a number, also make sure that there isn’t a currency amount in the input field. If someone puts in 1,422.00 it’s not a number and will fail since , is for decoration.
If someone puts in $1422.00 it’s not a number as $ is for decoration.
Either of these would fail the query.

answered May 28, 2019 at 17:07

Mark Fitzpatrick's user avatar

Mark FitzpatrickMark Fitzpatrick

1,6141 gold badge11 silver badges8 bronze badges

4

This would happen if someone types an apostrophe into the remarks field, which SQL server will interpret as the ending quote of the string. But much worse things can happen if the user knows a bit of sql and wants to cause trouble. For example, putting '-- in the remarks will result in

Update Table1 set treatment = 'blah', remarks = ''-- where lastName = 'foobar'

which will overwrite every row in the table, not only the one containing foobar.

Use query parameters so that user-provided values can’t be interpreted as query keywords and structure.

Instead of remarks = '" + appRemarks.Text + "' you will have remarks = @Remarks as well as

cmd.Parameters.Add("@Remarks", SqlDbType.NText).Value = appRemarks.Text;

and all the other user inputs likewise.

answered May 28, 2019 at 17:21

Ben Voigt's user avatar

Ben VoigtBen Voigt

278k43 gold badges420 silver badges721 bronze badges

Я получаю эту ошибку с одной из моих таблиц в базе данных:

(Исключение типа System.Data.OleDb.OleDbException произошло в System.Data.dll, но не было обработано в коде пользователя

Дополнительная информация: Ошибка синтаксиса в инструкции UPDATE.)

Это позволяет мне читать, но когда я прихожу, чтобы добавить новую запись или обновить ее с помощью SQL-запроса, она дает мне эту ошибку, я проверил, дважды проверял и triple проверял, но не вижу ничего плохого в этом… странно, что я взял его из другого стола, который, как я знаю, работал, и сделал все, чтобы изменить все переменные, но безрезультатно!

Извиняюсь, если вы все думаете, что это очень грязный код, его первый проект на первый год, и я все еще головаю быстрее, чем что-то делать!

Если бы кто-нибудь мог взглянуть на него и посмотреть, смогут ли они понять это, это было бы очень признательно!

Sub Update()

    Dim cs As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("mydatabasename") + ";"
    Dim cn As New OleDbConnection(cs)
    Dim cmd As OleDbCommand
    Dim r As OleDbDataReader
    Dim ite As String
    Dim siz As String
    Dim quantit As String
    Dim pric As String
    Dim sourc As String
    Dim updatestockstrings As String
    updatestockstrings = Request.QueryString("updatestock")
    ite = itm.Value
    siz = sze.Value
    quantit = qty.Value
    pric = prc.Value
    sourc = imgsrc.Value
    If ite = "" Then
        parMsg.InnerHtml = "Please add an item name"
    ElseIf siz = "" Then
        parMsg.InnerHtml = "Please add a size"
    ElseIf quantit = "" Then
        parMsg.InnerHtml = "Please add a quantity"
    ElseIf pric = "" Then
        parMsg.InnerHtml = "Please state a price"
    ElseIf sourc = "" Then
        parMsg.InnerHtml = "Please add an image source"
    Else
        cmd = New OleDbCommand("UPDATE Stocks Set Item='" & ite & "', Size='" & siz & "', Quantity='" & quantit & "', Price='" & pric & "', ImageSource='" & sourc & "' WHERE StockID=" & updatestockstrings & ";", cn)
        cn.Open()
        r = cmd.ExecuteReader()
        Do While r.Read()
        Loop
        cn.Close()
        parMsg.InnerHtml = "Update Successful!"
    End If
End Sub

How to fix “System.Data.OleDb.OleDbException: 'Syntax error in UPDATE statement.'”?

What I have tried:

public void btnUpdtLicens_Click_1(object sender, EventArgs e)
        {
            string conString = "Provider= Microsoft.Jet.OLEDB.4.0; Data Source=" + DBPath + ";";
            using (OleDbConnection con = new OleDbConnection(conString))
            {
                con.Open();
                if (con.State == ConnectionState.Open)
                {
                    foreach (DataGridViewRow row in LicenseAllctnGridView.Rows)
                    {

                        if (row.Cells[0].Value != null && row.Cells[1].Value != null)
                        {
                            OleDbDataAdapter _oda = new OleDbDataAdapter();
                            //string query = "update AllottedLicense set Department = " + row.Cells[0].Value.ToString() + ", AllottedLicense = " + row.Cells[1].Value.ToString() + ", where Department = " + row.Cells[0].Value.ToString() + "; ";
                            OleDbCommand cmd = new OleDbCommand("update AllottedLicense set Department = " + row.Cells[0].Value.ToString() + ", AllottedLicense = " + row.Cells[1].Value.ToString() + ", where Department = " + row.Cells[0].Value.ToString() + "", con);
                            _oda.SelectCommand = cmd;
                            cmd.ExecuteNonQuery();
                            cmd.Parameters.Clear();
                        }
                    }

                }
                con.Close();
        }
    }

the code for update is for storedprocedures in SQL server and may not work with access DB:

        string _Update_Emp = "UPDATE AlbahraniNetwork SET FirstName=@FirstName,SecondName=@SecondName,LastName=@LastName,Phone=@Phone,Cell=@Cell,Email=@Email,Address=@Address where FirstName=@FirstName";

        string appPath = Path.GetDirectoryName(Application.ExecutablePath);
        if (!appPath.EndsWith("\"))
            appPath += "\";
        _Conn.ConnectionString = (@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + appPath + "Database31.accdb");

        //_Conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:UsersAbdullahdocumentsvisual studio 2010ProjectsAlbahraniNetwork2AlbahraniNetwork2Database31.accdb";
        _Conn.Open();
        OleDbCommand _Update_Command = new OleDbCommand(_Update_Emp, _Conn);

        _Update_Command.Parameters.AddWithValue("@FirstName", FirstName.Text);
        _Update_Command.Parameters.AddWithValue("SecondName", SecondName.Text);
        _Update_Command.Parameters.AddWithValue("@LastName", LastName.Text);
        _Update_Command.Parameters.AddWithValue("@Phone", Phone.Text);
        _Update_Command.Parameters.AddWithValue("@Cell", Cell.Text);
        _Update_Command.Parameters.AddWithValue("@Email", Email.Text);
        _Update_Command.Parameters.AddWithValue("@Address", Address.Text);
        _Update_Command.ExecuteNonQuery();

Make it simple and instead use:

  string _Update_Emp = "UPDATE AlbahraniNetwork SET " +
       FirstName="" + FirstName.Text + """ +
       ",SecondName="" + SecondName.Text  + """ +
       ",LastName=""+ LastName.Text  + """ +
       ",Phone=""+ Phone.Text + """ +
       ",Cell="" + Cell.Text + """ +
       ",Email="" + Email.Text + """ +
       ",Address="" + Address.Text + """ +
       " where FirstName="" + FirstName.Text +";";

        string appPath = Path.GetDirectoryName(Application.ExecutablePath);
        if (!appPath.EndsWith("\"))
            appPath += "\";
        _Conn.ConnectionString = (@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + appPath + "Database31.accdb");

        //_Conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:UsersAbdullahdocumentsvisual studio 2010ProjectsAlbahraniNetwork2AlbahraniNetwork2Database31.accdb";
        _Conn.Open();
        OleDbCommand _Update_Command = new OleDbCommand(_Update_Emp, _Conn);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
if(analyse.data.Length == 1) { return; }
            string path = listBox1.SelectedItem.ToString().Substring(1); //Имя файла
            int id = GetId(path); //Получаем его id по имени
 
            string query = "SELECT COUNT(*) AS num FROM Gist_info WHERE ID_photo=" + id;
            dbCommand = new OleDbCommand(query, connection);
            OleDbDataReader reader = dbCommand.ExecuteReader();
 
            string imgData = "";
            string posData = "";
            for (int i = 0; i < analyse.data.Length-1; ++i) //заполняем массив позиций картинки и цвета в формате X:Y:X:Y и R:G:B:R:G:B
            {
                imgData += analyse.data[i].getColor().R + ":" + analyse.data[i].getColor().G + ":" + analyse.data[i].getColor().B + ":";
                posData += analyse.data[i].getPoint().X + ":" + analyse.data[i].getPoint().Y + ":";
            }
            imgData = imgData.Substring(0, imgData.Length - 1); //Удалить : в конце
            posData = posData.Substring(0, posData.Length - 1); //Удалить : в конце
 
            dbCommand = new OleDbCommand(query, connection);
            dbCommand.ExecuteNonQuery();
 
            string avR = analyse.getAverageGistogramm("R").ToString(); //Получаем данные для записи в бд
            string avG = analyse.getAverageGistogramm("G").ToString();
            string avB = analyse.getAverageGistogramm("B").ToString();
            string MedR = analyse.getMed()[0].ToString();
            string MedG = analyse.getMed()[1].ToString();
            string MedB = analyse.getMed()[2].ToString();
            string SgR = analyse.getSg()[0].ToString();
            string SgG = analyse.getSg()[1].ToString();
            string SgB = analyse.getSg()[2].ToString();
            string AllBright = analyse.getAvgBrightness().ToString();
 
 
            reader.Read();
            if ((int)reader["num"] != 0) //Если есть запись
            {
                query = "UPDATE Gist_info SET AllBright='" + AllBright + "', avR = '"+ avR + "', avG='" + avG + "', avB='" + avB + "', " +
                     "Img='" + imgData + "', Pos='" + posData +"', MedR='" + MedR + "', SgR='"+ SgR +
                     "', MedG='" + MedG +"', MedB='"+ MedB + "', SgG='"+ SgG + "', SgB='" + SgB + "' WHERE ID_photo=" + id;
            }
            else
            {
                /*query = "INSERT INTO Gist_info (ID_photo, AllBright, avR, avG, avB, Img, Pos, MedR, MedG, MedB, SgR, SgG, SgB) "
               + "VALUES ("+id+", '"+analyse.getAvgBrightness()+"', '"+avR+"', '"+avG+"', '"+avB+"', '"+imgData+"', '"+posData+"', " +
               "'"+MedR+"', '"+MedG+"', '"+MedB+"', '"+SgR+"', '" +SgG+"', '"+SgB+"')";*/
                query = "INSERT INTO Gist_info (ID_photo, AllBright, avR, avG, avB, Img, Pos, MedR, MedG, MedB, SgR, SgG, SgB) VALUES " +
                    "('"+id+"', '"+AllBright+"', '"+avR+"', '"+avG+"', '"+avB+"', '" + imgData+ "', '"+posData+"', '"+MedR+"', '"+MedG+"', '"+MedB+"', '"+SgR+"', '"+SgG+"', '"+SgB+"');";
            }
            reader.Close();
 
            /*try
            {*/
                dbCommand = new OleDbCommand(query, connection); //Здесь возникает ошибка
                dbCommand.ExecuteNonQuery();

I’m writing an application which stores user information. Currently the user is supposed to update their Name, Height, Weight and Birthday.

string height = TB_ClientHeight.Text;
string weight = TB_ClientWeight.Text;
string name = TB_ClientName.Text;
string bday = dateTimePicker1.Value.ToString("dd-MM-yyyy");
int heightint = Convert.ToInt32(height);
int weightint = Convert.ToInt32(weight);

It’s updated by calling the public static string username variable from another form and using that as the WHERE UserName = @username.

usernamestringo = Login.usernameFromLogin;

I’ve followed other SO answers in this context and corrected some issues (like preventing SQL Injection). However I’m still getting a syntax error while updating these fields as claimed by OleDbException.

using (OleDbConnection myCon = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=O:ReposDatabaseDatabase.accdb;Persist Security Info=False"))
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.CommandType = CommandType.Text;
string query = "UPDATE TPersons SET Name=@Name, SET Height=@Height, SET Weight=@Weight, SET Bday=@Bday " + " WHERE FirstName= @username";
cmd.CommandText = query;
cmd.Parameters.AddWithValue("@Name", name.ToString());
cmd.Parameters.AddWithValue("@Height", heightint.ToString());
cmd.Parameters.AddWithValue("@Weight", weightint.ToString());
cmd.Parameters.AddWithValue("@Bday", bday.ToString());
cmd.Parameters.AddWithValue("@username", usernamestringo);
cmd.Connection = myCon;
myCon.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Updated!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
cmd.Parameters.Clear();
}

The OleDbException is:

Index #0
NativeError: -526847407
Source: Microsoft Access Database Engine
SQLState: 3000
Description (message): Syntax error in UPDATE statement.

Could anyone guide me where my syntax is wrong? Thank you!

Logo
MurCode

  • Форумы
  • Поиск
  • О проекте

ANF76

Дата: 09.03.2005 17:05:49

Хочу обновить запись в талице Login, а она мне выдает ошибку:

Exception Details: System.Data.OleDb.OleDbException: Ошибка синтаксиса в инструкции UPDATE.

<%@ Page Language=»VB» Debug=»true» %>
<%@ import Namespace=»System.Data» %>
<%@ import Namespace=»System.Data.OLEDB» %>

<script runat=»server»>

Sub SubmitBut1_Click(sender As Object, e As EventArgs)
Dim DBConn as OleDbConnection
Dim DBUpdate As New OleDbCommand
DBConn = New OleDbConnection («Provider=Microsoft.Jet.OLEDB.4.0; Ole DB Services=-4; Data Source=C:\web\Orion_!»& _
«.mdb»)

DBUpdate.CommandText = «Update Login Set Password = 23131 Where Name = ‘fedorov’”
DBUpdate.Connection = DBConn
DBUpdate.Connection.Open
DBUpdate.ExecuteNonQuery()
End Sub

gerss

Дата: 09.03.2005 17:55:43

А password у тебя не текстовое поле часом? Возьми значение в кавычки тогда.

Сергей

Никита А. Зимин

Дата: 10.03.2005 07:33:51

В вашем SQL-выражении использовано несколько объектов, названия которых совпадают с зарезервированными словами MSAccess. Исправьте выражение:

UPDATE Login SET [Password] = '23131' WHERE [Name] = ‘fedorov’

Никита А. Зимин

Дата: 10.03.2005 07:35:21

Еще кстати — после копирования вашего выражения заметил, что слово fedorov ограничено не прямыми апострофами, а наклонными.

ANF76

Дата: 10.03.2005 15:26:18

Большое спасибо, все заработало.

Понравилась статья? Поделить с друзьями:
  • System data oledb oledbexception ошибка синтаксиса в инструкции insert into
  • Systec таймер механический инструкция для включения и выключения электроприборов
  • Systane hydration глазные капли инструкция
  • Syspur derm инструкция по применению
  • Sysperl v30 инструкция на русском