2013-01-11 36 views
-1

我有以下代碼:更新值:SQL - APSX

更新

try 
    { 
     ArticleId = Request.QueryString["ArticleId"].ToString(); 
     NewArticleTitle = Request.Form["ArticleTitle"].ToString(); 
     NewArticleDate = Request.Form["ArticleDate"].ToString(); 
     NewArticleBody = Request.Form["ArticleBody"].ToString(); 


     string dpath = Server.MapPath(@"App_Data") + "/MySite.mdb"; 
     string connectionstring = @"Data source='" + dpath + "';Provider='Microsoft.Jet.OLEDB.4.0';"; 
     OleDbConnection con = new OleDbConnection(connectionstring); 
     string QuaryString = String.Format("update tblarticles set articletitle='{0}', articlebody='{1}', postdate='{2}' where articleid={3}", NewArticleTitle, NewArticleBody, NewArticleDate, ArticleId); 
     OleDbCommand cmd = new OleDbCommand(QuaryString, con); 
     OleDbDataAdapter da = new OleDbDataAdapter(cmd); 
     DataSet ds = new DataSet(); 
     da.Fill(ds, "tbl"); 
     con.Close(); 
     Response.Redirect("ArticlesTable.aspx"); 
    } 
     catch { } 

的條款ArticleID爲自增列(數量型) 當它得到這條線da.Fill(ds, "tbl");該計劃coutinue到漁獲。 我的quastion是如何防止它,所以表會真正更新? 希望得到幫助,謝謝!

+1

您可能想要捕獲異常(例如,catch(Exception ex){Response.Write(ex.Message);}')以查看發生了什麼。 –

回答

1

由於ArticleId是數字,所以你需要替換此:

where ArticleId='{3}' 

有了這個:

where ArticleId={3} 

所以,你的where子句中應該是這樣的:

"update tblArticles set ArticleTitle='{0}', ArticleBody='{1}',PostDate='{2}' where ArticleId={3}" 
+0

謝謝,我改變了它,但爲什麼我仍然遇到同樣的問題? –

+0

,因爲Yaqub提供的答案是不正確的..當你的文本已經用雙重qoutes包裝時,你爲什麼需要單引號的Params ..這個答案不正確 – MethodMan

+0

@DJKRAZE:它會導致------ 更新tblarticles設置articletitle ='someValue',articlebody ='someValue',postdate ='someValue'where articleid = 1 那麼最新錯了? –

1

如果ArticleId是數據類型數字,那麼你必須刪除它周圍的引號。相反的:

where ArticleId='{3}' 

試試這個:

where ArticleId = {3} 

但是,你不應該這樣做這種方式。嘗試使用準備好的語句或參數化查詢,而不是String.Format

+0

謝謝,我將它改爲「where ArticleId = {3}」,但我仍然遇到同樣的問題,爲什麼? –

+0

@NaveTseva你可以請你發佈你的例外嗎?在執行之前也嘗試打印查詢並直接進行測試。 –

+0

沒有任何錯誤,這個問題就是它堆棧在這一行「da。填充(ds,「tbl」);「和cotinue到」catch「 –

0

參數插入是一個壞主意。這是對sql injection打開的潛在有害代碼。使用參數代替參數插入。 Sql參數對於快速查找錯誤也很有用。由於參數強類型化,並且不能將字符串作爲數值參數的參數傳遞。