2012-07-09 94 views
1

首先讓我告訴你,我已經搜索了至少一天的awnsers,所以我最終認爲讓我們試試看。SQL ASP.NET插入麻煩

我想爲一個學校項目創建這個購物車,但我正在使用代碼。老師(sql)告訴我檢查數據庫,並且出現了一些錯誤(不是我的錯)。我修復了這些小錯誤。

現在,當我只是做SELECT xxxx FROM xxx =沒有錯誤,一切都顯示在gridview中。 當我添加第二部分時,我得到一個「FROM子句中的語法錯誤」。 加上第三部分和排除第二部分是一樣的錯誤。

也許我能想出是數據庫中的這個小東西的唯一的事情: 字段屬性 一般 索引:是(無重複)

它可能是一些小的,但它是推動我堅果,所以任何幫助非常感謝。

下面是相關代碼:

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

     } 

回答

3

你必須表名WHERE子句之間加空格。

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

使用參數避免這樣的問題,SQL Injection.

cmd.CommandText = "SELECT prijs , product_id FROM Product WHERE [email protected]"; 
    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; 
+0

+1由於您使用C#,使用字符串字面量來避免這樣的煩惱。他們可以跨越多行。 '@「選擇prijs ...」' – dwerner 2012-07-09 02:30:40

+0

從一開始就使用參數您會受益匪淺。這只是一個好習慣和最佳實踐。 – NinjaBomb 2012-07-09 02:37:10

+2

@AVD,謝謝!我的意思是你真的讓我從2天的壓力中解脫出來。謝謝!! – 2012-07-09 02:46:21