Adding to database using Oledb Syntax error in INSERT INTO statement

StackOverflow https://stackoverflow.com/questions/23326967

  •  10-07-2023
  •  | 
  •  

Вопрос

when i hit the add button to insert a new book, i get an error at cmd.ExecuteNonQuery(); Syntax error in INSERT INTO statement. Am i missing anything?

protected void btnAddBook_Click(object sender, EventArgs e)
            {
                string connect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|Bookdb.accdb";
                using (OleDbConnection conn = new OleDbConnection(connect))
                {
                    OleDbCommand cmd = new OleDbCommand("INSERT INTO Books (Title, Author, Price, Edition) VALUES (@Title, @Author, @Price, @Edition)");
                    cmd.CommandType = CommandType.Text;
                    cmd.Connection = conn;
                    cmd.Parameters.AddWithValue("@Title", TextBox1.Text);
                    cmd.Parameters.AddWithValue("@Author", TextBox2.Text);
                    cmd.Parameters.AddWithValue("@Price", TextBox3.Text);
                    cmd.Parameters.AddWithValue("@Edition", TextBox4.Text);


                    conn.Open();
                    cmd.ExecuteNonQuery();
                    conn.Close();
                }
Это было полезно?

Решение

The only reason that I can find as a possible failure for your code is if the Price field is a numeric field in your database table. You are creating a parameter with AddWithValue and this method creates a parameter whose datatype is derived from the datatype of the value passed. You pass a string (TextBox3.Text) and so AddWithValue creates a string parameter.

You could try to force the AddWithValue to create a numeric parameter with

 cmd.Parameters.AddWithValue("@Price", Convert.ToDecimal(TextBox3.Text));

(Of course assuming a decimal Price column)

Другие советы

Right before you call conn.Open(), you need to call cmd.Prepare(), so that all the parameters you set are actually loaded into the SQL statement.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top