2012-11-09 105 views
-1

我試圖用下面的方法將記錄插入到數據庫中。我在按鈕單擊事件中調用此方法,但由於某些原因沒有插入記錄。爲什麼我的插入沒有在數據庫中插入記錄

有四個字段需要插入:rpttemplateid - 我從另一個數據庫表中獲取該字段,其他所有字段只是靜態值。

我在下面做錯了什麼?

public void updatereporttemplate() 
{ 
    string cnn = WebConfigurationManager.ConnectionStrings["Underwriting"].ConnectionString; 
    SqlConnection cnn1 = new SqlConnection(cnn); 
    cnn1.Open(); 
    string getrptdesc = "select max(rptdesc) + 1 from report_description where rptdesc < 999 and rptdesc is not null"; 
    SqlCommand cmd = new SqlCommand(getrptdesc, cnn1); 
    SqlDataReader sdr = cmd.ExecuteReader(); 
    sdr.Read(); 

    int getcount = int.Parse(sdr[0].ToString()); 
    sdr.Close(); 
    string commandtext1 = "INSERT INTO report_template" + "(rpttemplateid,rpttemplatedescr,minsubs,minmebers) " + 
      " Values(" + getcount + "," + " " + " , " + 0 + "," + 0 + ")"; 
    SqlCommand command1 = new SqlCommand 
    { 
     CommandText = commandtext1, 
     Connection = cnn1 

    }; 
+2

你在哪裏執行INSERT查詢字符串? –

+0

Iam在按鈕clcick事件中執行插入 –

+1

不,但您需要在command1對象上調用execute()對嗎?否則command1將如何插入? –

回答

0

你需要打開連接

cnn1.Open(); 

然後執行命令

command1.ExecuteNonQuery(); 
+0

我改變了我的方法到下面,現在得到一個錯誤 –

+0

什麼是錯誤? – Cityonhill93

+0

描述:執行當前Web請求期間發生未處理的異常。請查看堆棧跟蹤以獲取有關該錯誤的更多信息以及源代碼的位置。 異常詳細信息:System.Data.SqlClient.SqlException:','附近的語法不正確。 Source Error: Line 145: Line 146:SqlCommand command1 = new SqlCommand(commandtext1,cnn2); 第147行:command1.ExecuteNonQuery(); 148行:cnn2.Close(); 149行: –

2

你缺少command1.ExecuteNonQuery();

另外,你認爲在你的表使用IDENTITY列,而不是試圖手動設置計數?如果該頁面被多個人同時擊中怎麼辦?

+0

我添加了command1.executenonquery(),現在得到一個錯誤 –

+0

確保你的連接是開放的 – MikeSmithDev

+0

你的insert語句可能會丟失一些東西:嘗試在第二個值中放入「''」。 「+」,「+」,「+ 0 +」,「+ 0 +」);這是報價+單引用+單引用+報價 – MikeSmithDev

相關問題