2016-09-12 70 views
-3

在Sql中有一個名爲Student的表,其中定義了4列。第一列是通過身份自動遞增的ID。當我嘗試插入SQL數據,然後我得到以下錯誤: 「關鍵字‘其中’附近有語法錯誤」關於SqlCommandBuilder如何在使用sqlcommandbuilder對象的sql server中插入新行

protected void Button1_Click(object sender, EventArgs e) 
    { 
     string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString; 
     SqlConnection con = new SqlConnection(cs); 

     string sqlQuery = "insert into Student values where = " + TextStudentID.Text; 

     SqlDataAdapter da = new SqlDataAdapter(sqlQuery, con); 

     SqlCommandBuilder builder = new SqlCommandBuilder(da); 

     DataSet ds = (DataSet)ViewState["dataset"]; 

     SqlCommand cmd = builder.GetInsertCommand(); 
     cmd.Parameters["@StudentName"].Value = TextStudentName.Text; 
     cmd.Parameters["@Gender"].Value = DropDownList1.SelectedValue; 
     cmd.Parameters["@Studentmarks"].Value = TextStudentName.Text; 

     cmd.ExecuteNonQuery(); 

     da.Fill(ds); 
    } 

感謝的對象提前

+0

請閱讀[上INSERT語句文件(https://msdn.microsoft.com/en-us/library/ms174335.aspx),你會看到,有沒有像你正在試圖做的那樣使用'WHERE'。 – Filburt

回答

0

你插入語法不正確。假設你的ID是主鍵(身份證),你的插入語句應該是這樣的:

string sqlQuery = "insert into Student (StudentName, Gender, Studentmarks) values (@StudentName, @Gender, @Studentmarks)"; 

的ID會自動插入,並與你逝去的其他值自動遞增。

你應該清理一下你的代碼,並把你的SqlConnection放在使用區塊中,以便正確處理它。

using (SqlConnection con = new SqlConnection(cs)) 
{ 
    // your code 
} 

https://www.dotnetperls.com/sqldataadapter

如果你要的參數添加到您的命令的方式,你需要使用AddWithValue,但要注意的錯誤隱式類型轉換的可能性。

例子:

cmd.Parameters.AddWithValue("@StudentName", TextStudentName.Text); 
相關問題