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

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();
  • Remove From My Forums
  • Question

  • I have one code for updating the password, however the code is giving the error that «Syntax error in UPDATE statement.», before this I was getting error «Syntax
    error in Insert into statement
    » which was solved by «Noam B«, the link to that page is

    here. Now i am getting these error. I tried to solve it but no success, can you guys help me once again. 

    The code that I have written is:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using System.Data.OleDb;
    
    namespace Cyber_Application
    {
        public partial class ChangePassword : Form
        {
            string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Cyber Application\param.accdb; Jet OLEDB:Database Password=123456";
    
            public ChangePassword()
            {
                InitializeComponent();
            }
    
            private void changePassword()
            {
                OleDbConnection cn = new OleDbConnection(connectionString);
                cn.Open();
                string scmd1 = "UPDATE EnterSoftware set Password = '" + txtNewPassword.Text + "' where UserName = 'admin'";
                OleDbCommand cmd1 = new OleDbCommand(scmd1, cn);
                OleDbDataReader sdr1 = cmd1.ExecuteReader();
                cn.Close();
                MessageBox.Show("Password has been changed successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.Close();
            }
    
            private void btnOk_Click(object sender, EventArgs e)
            {
                OleDbConnection cn = new OleDbConnection(connectionString);
                cn.Open();
                string scmd = "select Password from EnterSoftware";
                OleDbCommand cmd = new OleDbCommand(scmd, cn);
                OleDbDataReader sdr = cmd.ExecuteReader();
    
                while (sdr.Read())
                {
                    if (txtCurrentPassword.Text == sdr["Password"].ToString())
                    {
                        if (txtNewPassword.Text == "" || txtConfirmPassword.Text == "")
                        {
                            MessageBox.Show("Password cannot be blank", "Change Password Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
    
                        if (txtNewPassword.Text == txtConfirmPassword.Text && txtNewPassword.Text != "" || txtConfirmPassword.Text != "")
                        {
                            changePassword();
                        }
                        else
                        {
                            MessageBox.Show("Password do not match", "Change Password Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            txtCurrentPassword.Text = "";
                            txtNewPassword.Text = "";
                            txtConfirmPassword.Text = "";
                            txtCurrentPassword.Focus();
                        }
                    }
    
                    else
                    {
                        MessageBox.Show("Invalid Current Password", "Change Password Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        txtCurrentPassword.Text = "";
                        txtNewPassword.Text = "";
                        txtConfirmPassword.Text = "";
                        txtCurrentPassword.Focus();
                    }
                }
                cn.Close();
            }
        }
    }
    
    

    The error code is as below:

    System.Data.OleDb.OleDbException was unhandled
      Message=Syntax error in UPDATE statement.
      Source=Microsoft Office Access Database Engine
      ErrorCode=-2147217900
      StackTrace:
           at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr)
           at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult)
           at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult)
           at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult)
           at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method)
           at System.Data.OleDb.OleDbCommand.ExecuteReader(CommandBehavior behavior)
           at System.Data.OleDb.OleDbCommand.ExecuteReader()
           at Cyber_Application.ChangePassword.changePassword() in E:ClientsS V Cyber CafeCyber ApplicationCyber ApplicationChangePassword.cs:line 27
           at Cyber_Application.ChangePassword.btnOk_Click(Object sender, EventArgs e) in E:Cyber ApplicationChangePassword.cs:line 52
           at System.Windows.Forms.Control.OnClick(EventArgs e)
           at System.Windows.Forms.Button.OnClick(EventArgs e)
           at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
           at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
           at System.Windows.Forms.Control.WndProc(Message& m)
           at System.Windows.Forms.ButtonBase.WndProc(Message& m)
           at System.Windows.Forms.Button.WndProc(Message& m)
           at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
           at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
           at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
           at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
           at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
           at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
           at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
           at System.Windows.Forms.Application.RunDialog(Form form)
           at System.Windows.Forms.Form.ShowDialog(IWin32Window owner)
           at System.Windows.Forms.Form.ShowDialog()
           at Cyber_Application.MainForm.changePasswordToolStripMenuItem_Click(Object sender, EventArgs e) in E:ClientsS V Cyber CafeCyber ApplicationCyber ApplicationMainForm.cs:line 79
           at System.Windows.Forms.ToolStripItem.RaiseEvent(Object key, EventArgs e)
           at System.Windows.Forms.ToolStripMenuItem.OnClick(EventArgs e)
           at System.Windows.Forms.ToolStripItem.HandleClick(EventArgs e)
           at System.Windows.Forms.ToolStripItem.HandleMouseUp(MouseEventArgs e)
           at System.Windows.Forms.ToolStripItem.FireEventInteractive(EventArgs e, ToolStripItemEventType met)
           at System.Windows.Forms.ToolStripItem.FireEvent(EventArgs e, ToolStripItemEventType met)
           at System.Windows.Forms.ToolStrip.OnMouseUp(MouseEventArgs mea)
           at System.Windows.Forms.ToolStripDropDown.OnMouseUp(MouseEventArgs mea)
           at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
           at System.Windows.Forms.Control.WndProc(Message& m)
           at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
           at System.Windows.Forms.ToolStrip.WndProc(Message& m)
           at System.Windows.Forms.ToolStripDropDown.WndProc(Message& m)
           at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
           at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
           at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
           at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
           at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
           at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
           at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
           at System.Windows.Forms.Application.Run(Form mainForm)
           at Cyber_Application.Program.Main() in E:ClientsS V Cyber CafeCyber ApplicationCyber ApplicationProgram.cs:line 17
           at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
           at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
           at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
           at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
           at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
           at System.Threading.ThreadHelper.ThreadStart()
      InnerException: 
    
    

    • Edited by

      Monday, September 26, 2011 9:59 AM

Answers

  • The EnterSoftware 
    table contains a column named Password which is one reserved word.

    Use curly braces [Password]

    string scmd1 = "UPDATE EnterSoftware set [Password] = '" + txtNewPassword.Text + "' where UserName = 'admin'";

    • Edited by
      Zain_Ali
      Monday, September 26, 2011 10:04 AM
    • Marked as answer by
      tapan.desai
      Monday, September 26, 2011 10:09 AM

    • Marked as answer by
      tapan.desai
      Monday, September 26, 2011 10:12 AM

I am getting this error while trying to update but I am not able to find any issue in update statement.

str = "UPDATE BillTable SET Bill_No = @billno, Bill_Year = @billYear, Voucher_No= @voucher, Date= @date, Group_ID= @groupname, Vendor_Id= @vendorname, Amount= @amount WHERE ID= @billID";

            cmd = new OleDbCommand(str, cn);
            cmd.Parameters.Add(new OleDbParameter("@billID", Convert.ToString(inovidid)));
            cmd.Parameters.Add(new OleDbParameter("@billYear", Convert.ToString(fylabel.Text)));
            cmd.Parameters.Add(new OleDbParameter("@billno", Convert.ToString(billno.Text)));
            cmd.Parameters.Add(new OleDbParameter("@voucher", Convert.ToString(voucher.Text)));
            cmd.Parameters.Add(new OleDbParameter("@date", Convert.ToString(DateTimePicker1.Text)));
            cmd.Parameters.Add(new OleDbParameter("@groupname", Convert.ToString(groupidDB)));
            cmd.Parameters.Add(new OleDbParameter("@vendorname", Convert.ToString(vendoridDB)));
            cmd.Parameters.Add(new OleDbParameter("@amount", Convert.ToString(amount.Text)));


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();
        }
    }

Я работал в приложении формы C # с базой данных MS-Access mdb. У меня есть база данных, в которой есть таблица Customers с двумя столбцами CustomerId и Balance. Оба столбца имеют тип данных integer.

Я получал ошибку

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

в System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling (OleDbHResult hr)
в System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult (tagDBPARAMS dbParams, Object & executeResult)
в System.Data.OleDb.OleDbCommand.ExecuteCommandText (Object & executeResult)
в System.Data.OleDb.OleDbCommand.ExecuteCommand (поведение CommandBehavior, Object и executeResult)
в System.Data.OleDb.OleDbCommand.ExecuteReaderInternal (поведение CommandBehavior, метод String)
в System.Data.OleDb.OleDbCommand.ExecuteNonQuery ()
в xml_and_db_test.Form1.button1_Click (отправитель объекта, EventArgs e) в G: my Documents Visual Studio 2008 Projects xml_and_db_test xml_and_db_test Form1.cs: строка 45

Коды, которые я пробовал до сих пор:

try
{
   OleDbConnection con = new 
   OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\database_for_kissan_Pashu_AhaR_Bills.mdb");

   int balance = Convert.ToInt32(textBox2.Text);
   int id = Convert.ToInt32(textBox1.Text);

   // int recordnumb = int.Parse(recordTextBox.Text);

   //  OleDbConnection oleDbConnection = new            OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Checkout-1\Documents\contact.accdb");    
   OleDbCommand update = new OleDbCommand("UPDATE Customers  SET Balance = '" + balance + "',  WHERE id = " + id + " ", con);

   con.Open();
   update.ExecuteNonQuery();
   con.Close();

   // string queryText = "UPDATE Customers SET Balance = ?, where CustomerId = ?;";
   //string queryText = " 'UPDATE Customers SET Balance =' " + balance+ " ' WHERE CustomerId=  ' " +  id +  " ' " ;

   //OleDbCommand cmd = new OleDbCommand(queryText, con);
   //cmd.CommandType = CommandType.Text;
   //cmd.Parameters.AddWithValue("@balance", Convert.ToInt32(textBox2.Text));
   //cmd.Parameters.AddWithValue("@ID", Convert.ToInt32(textBox1.Text));
   //cmd.Parameters.Add("Balance", OleDbType.Integer).Value = Convert.ToInt32(textBox2.Text);
   //cmd.Parameters.Add("CustomerId", OleDbType.Integer).Value = Convert.ToInt32(textBox1.Text);

   //con.Open(); // open the connection
   ////OleDbDataReader dr = cmd.ExecuteNonQuery();

   //int yy = cmd.ExecuteNonQuery();
   //con.Close();
}
catch (Exception ex)
{
    string c = ex.ToString();
    MessageBox.Show(c);
}

//try
//{
//    OleDbConnection con = new OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0; Data Source = G:\my Documents\Visual Studio 2008\Projects\xml_and_db_test\xml_and_db_test\bin\Debug\database_for_kissan_Pashu_AhaR_Bills.mdb");
//    string queryText = "UPDATE Customers SET Balance = ?, where CustomerId = ?;";

//    OleDbCommand cmd = new OleDbCommand(queryText, con);
//    cmd.CommandType = CommandType.Text;
//    //cmd.Parameters.AddWithValue("@balance", Convert.ToInt32(textBox2.Text));
//    //cmd.Parameters.AddWithValue("@ID", Convert.ToInt32(textBox1.Text));

//    cmd.Parameters.Add("Balance", OleDbType.Integer).Value = Convert.ToInt32(textBox2.Text);

//    cmd.Parameters.Add("CustomerId", OleDbType.Integer).Value = Convert.ToInt32(textBox1.Text);
//    con.Open(); // open the connection
//    //OleDbDataReader dr = cmd.ExecuteNonQuery();

//    int yy = cmd.ExecuteNonQuery();
//    con.Close();

//}
//catch (Exception ex)
//{
//    string c = ex.ToString();
//    MessageBox.Show(c);

//}
//string connetionString = null;
//OleDbConnection connection;
//OleDbDataAdapter oledbAdapter = new OleDbDataAdapter();
//string sql = null;
//connetionString = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source = G:\my Documents\Visual Studio 2008\Projects\xml_and_db_test\xml_and_db_test\bin\Debug\database_for_kissan_Pashu_AhaR_Bills.mdb;";
//connection = new OleDbConnection(connetionString);
//sql = "update Customers set Balance = '1807' where CustomerId = '1'";
//try
//{
//    connection.Open();
//    oledbAdapter.UpdateCommand = connection.CreateCommand();
//    oledbAdapter.UpdateCommand.CommandText = sql;
//    oledbAdapter.UpdateCommand.ExecuteNonQuery();
//    MessageBox.Show("Row(s) Updated !! ");
//    connection.Close();
//}
//catch (Exception ex)
//{
//    MessageBox.Show(ex.ToString());
//}

Некоторые коды находятся в комментариях, а некоторые — при каждом методе, я получаю одну и ту же ошибку.

5 ответов

Лучший ответ

Как сказал gzaxx .. Попробуйте изменить это

string queryText = "UPDATE Customers SET Balance = ?, where CustomerId = ?;";

С участием

string queryText = "UPDATE Customers SET Balance = ? where CustomerId = ?;";


5

matzone
2 Июл 2013 в 16:40

  OleDbCommand o_cmd = new OleDbCommand("Update tbl_SalesTax 
                       set tbl_SalesTax.SerialNumber='" + txtSerialNo.Text + "'
                      ,tbl_SalesTax.PartyCode='" + txtPartyCode.Text + "'
                      ,tbl_SalesTax.PartyName='" + txtPartyName.Text + "'
                      ,tbl_SalesTax.TinNumber='" + txtTinNo.Text + "'
                      ,tbl_SalesTax.Gr='" + cmbgr.Text + "'
                      ,tbl_SalesTax.Qty='" + txtQty.Text + "'
                      ,tbl_SalesTax.Price='" + txtPrice.Text + "'
                      ,tbl_SalesTax.Basic='" + txtBaisc.Text + "'
                      ,tbl_SalesTax.Value='" + txtValue.Text + "'
                      ,tbl_SalesTax.Total='" + txtTotal.Text + "'
                      ,tbl_SalesTax.Bags='" + txtBags.Text + "'
                      ,tbl_SalesTax.DumpCode='" + txtDumpCode.Text + "'
         where tbl_SalesTax.BookNumber='" + txtBookNo.Text + "'", my_con);


1

ρяσѕρєя K
29 Янв 2016 в 07:08

Вы просто измените это на

OleDbCommand update = new OleDbCommand («UPDATE Customers SET [Balance] = ‘» + balance + «‘, WHERE [id] =» + id + «», con);

И ваш код будет работать правильно


1

Amit Bhati
5 Мар 2014 в 13:53

Избавьтесь от запятой после предложения set — у вас обновляется только одна переменная. установить xxx = xxx, где должно быть установлено xxx = xxx, где.

OleDbCommand update = new OleDbCommand("UPDATE Customers  SET Balance = '" + balance + "'  WHERE id = " + id + " ", con);


3

tsells
2 Июл 2013 в 16:31

В вашем запросе после баланса стоит запятая. Также вы переводите свой баланс на int32, но вставляете его как строку из-за одинарных кавычек между ними.

"UPDATE Customers  SET Balance = " + balance + "  WHERE id = " + id

Этот запрос должен работать.


4

gzaxx
2 Июл 2013 в 16:33

«Ошибка синтаксиса в инструкции UPDATE.», хотя вроде всё написано правильно.

private void button1_Click(object sender, EventArgs e)
        {
            string connectString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=BD1.mdb";
            con = new OleDbConnection(connectString);
            con.Open();
            string query = "";
            if (frm.radVal == 0)
            {
                query = string.Format("UPDATE Developers SET Developer_name = '" + textBox1.Text +"', Developer_specialty = '"+ textBox3.Text +"', team_id = "+ textBox2.Text +", Password = '"+ textBox4.Text +"' WHERE Developer_id = "+ id +";");
            }
            else if (frm.radVal == 1)
            {
                query = "UPDATE Managers SET Manager_name = '" + textBox1.Text + "', Admin_id = '" + textBox3.Text + "', Password = '" + textBox2.Text + "' WHERE Manager_id = '" + id + "'";
            }
            else if (frm.radVal == 2)
            {
                query = "UPDATE Admins SET Admin_name = '" + textBox1.Text + "', Password = '" + textBox2.Text + "' WHERE Admin_id = '" + id + "'";
            }

            cmd = new OleDbCommand(query, con);
            MessageBox.Show(query);
            int number = cmd.ExecuteNonQuery();
            Console.WriteLine("Обновлено объектов: {0}", number);
            //MessageBox.Show(cmd.ExecuteScalar().ToString());
            if (button1.Focused)
            {
                MessageBox.Show("Данные успешно обновлены");
            }

        }

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

(Исключение типа 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

Понравилась статья? Поделить с друзьями:

А вот и еще наши интересные статьи:

  • Акупунктурная массажная ручка инструкция по применению
  • Холодильник атлант мхм 1744 01 инструкция по эксплуатации
  • Раскоксовка валера в масло инструкция по применению
  • Руководство audacity скачать бесплатно
  • Руководство еат березка

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии