Big.S
Big.S

Reputation: 13

SQL ASP.NET Insert troubles

First let me tell you that i have searched at least a day long for awnsers, so i finally thought lets give this a try.

I am trying to create this shoppingcart for a schoolproject, but i am struggeling with the code. A teacher (sql) told me to check the database and there were some mistakes (not my fault). I fixed these small errors.

Now when i just do SELECT xxxx FROM xxx = no errors, everything show in the gridview. when i add the 2nd part i get a "Syntax error in FROM clause". adding the 3rd part and excluding 2nd part is same error.

Maybe the only thing i could come up with was this little thing in the database: Field properties General Indexed: Yes(No Duplicates)

its probably something minor, but it is driving me nuts, so any help is very much appreciated.

Here is the relevant code:

protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["add"] == null)
            {
                Response.Redirect("producten.aspx");
            }
            else
            {
                Label a = new Label();
                a.Text = Request.QueryString["add"];
                lbl_testing.Text = a.Text;

                OleDbConnection conn = new OleDbConnection();
                conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; "
                    + "Data Source=|DataDirectory|webwinkel.accdb";

                OleDbCommand cmd = new OleDbCommand();
                cmd.Connection = conn;
                cmd.CommandText = "SELECT prijs , product_id FROM Product" +
                                  "WHERE product_id ='" + lbl_testing.Text + "'";

                //"INSERT INTO Orderregels(prijsperstuk, product_id)" +

                try
                {
                    conn.Open();
                    OleDbDataReader reader = cmd.ExecuteReader();
                    Label1.Text = "";
                    GridView1.DataSource = reader;
                    GridView1.DataBind();
                    reader.Close();
                }
                catch (Exception exc)
                {
                    Label1.Text = exc.Message;
                }
                finally
                {
                    conn.Close();
                }
            }

        }

Upvotes: 1

Views: 110

Answers (1)

KV Prajapati
KV Prajapati

Reputation: 94645

You have to add spaces between TableName and WHERE clause.

cmd.CommandText = "SELECT prijs , product_id FROM Product " 
                         + "WHERE product_id ='" + lbl_testing.Text + "'";

Use parameters to avoid such issues and SQL Injection.

  cmd.CommandText = "SELECT prijs , product_id FROM Product WHERE product_id=@productid";
  cmd.Parameters.Add("@productid",OleDbType.VarChar,10).Value=lbl_testing.Text;
  //if Id is `numeric` type then use
  //cmd.Parameters.Add("@productid",OleDbType.Integer.Value=lbl_testing.Text;

Upvotes: 3

Related Questions