Frage

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();
                }
War es hilfreich?

Lösung

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)

Andere Tipps

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top