![](/img/trans.png)
[英]SQL Server Insert Error: Column name or number of supplied values does not match table definition c#
[英]SQL Server Insert Error: Column name or number of supplied values does not match table definition
我正在嘗試使用Microsoft Visual Studio 2012將數據添加到SQL Server中的表。但是,它給了我這個錯誤:
SQLException未被用戶代碼解開。
列名或提供的值數與表定義不匹配。
這是我的代碼:
protected void btnAdd_Click(object sender, EventArgs e)
{
con.Open(); // establish a database connection
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText =
"INSERT INTO Products VALUES (@CatID, @Name, " +
"@Image, @Description, @Price)";
cmd.Parameters.Add("@CatID", SqlDbType.Int).Value =
ddlCategories.SelectedItem.Value;
cmd.Parameters.Add("@Name", SqlDbType.NVarChar).Value =
txtName.Text;
cmd.Parameters.Add("@Image", SqlDbType.NVarChar).Value =
"http://localhost:12345/CAPSTONE/images/" + fuImage.FileName;
cmd.Parameters.Add("@Description", SqlDbType.NVarChar).Value =
txtDescription.Text;
cmd.Parameters.Add("@Price", SqlDbType.Decimal).Value =
txtPrice.Text;
// saving the image file to your website folder 'Images'
fuImage.SaveAs(Server.MapPath("~/images/" + fuImage.FileName));
cmd.ExecuteNonQuery();
con.Close();
Response.Redirect("Default.aspx");
}
在你使用這個方法時,你必須在你的查詢中創建數據庫表的所有列(如果它是自動增量,則不要輸入Id的值)
"INSERT INTO Products VALUES (@CatID, @Name, " +
"@Image, @Description, @Price)";
你只有5列,而且CatID不是自動增量值! 你必須檢查一下,如果是真的!
並且您可以選擇要通過此查詢創建的值
cmd.CommandText ="INSERT INTO Products (CatID, Name,Image, Description, Price)
VALUES (@CatID, @Name,@Image, @Description, @Price)";
如果它的值設置為自動遞增,則仔細檢查Products表的主鍵(我假設您的產品ID)(Identity Specification> Is Identity = true)
這意味着您的Products
表的列數多於您在VALUES
語句中提供的列數。
(@CatID, @Name, @Image, @Description, @Price)
如果在management studio中執行查詢sp_columns Products
,它將列出表中的所有列。
但是,如果您只想插入這些值,則需要執行以下查詢:
INSERT Products (CatID, Name, Image, Description, Price)
如果指定INSERT
語句而未指定列名,則需要填充所有列
使用try catch block,並找出catch中的確切問題,它會說出你遺漏的內容,其余的大部分可能的答案已在上面給出
private void btninsert_Click(object sender, EventArgs e)
{
try
{
con.Open();
cmd = new SqlCommand("insert into Empinfo values ('" + textBox1.Text + "''" + textBox2.Text + "''" + textBox3.Text + "''" + textBox4.Text + "')", con);
cmd.ExecuteNonQuery();
MessageBox.Show("Insert the record");
cmd.Dispose();
}
catch(Exception e1)
{
MessageBox.Show("e1");
}
finally
{
con.Close();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.