【发布时间】:2016-02-28 00:05:44
【问题描述】:
由于某种原因,result 始终是-1,并且没有任何内容添加到数据库中。我在 SQL Server 中执行了查询,它运行良好。我没有得到任何异常,也没有使用任何存储过程。
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=RAINBOW;Integrated Security=True");
SqlCommand cmd;
cmd = new SqlCommand("INSERT INTO ItemDetails.item(description,category_id) VALUES (@item_desc,@cat_id)", con);
cmd.Parameters.AddWithValue("@item_desc", txtitemdesc.Text);
cmd.Parameters.AddWithValue("@cat_id", GetCategoryID());
try
{
con.Open();
int result = cmd.ExecuteNonQuery();
if (result > 0)
{
MessageBox.Show("Record Inserted Successfully!");
}
else
{
MessageBox.Show("Failed to add record");
}
}
catch (SqlException ex)
{
MessageBox.Show("An error has occured! " + ex);
}
finally
{
con.Close();
}
编辑
int GetCategoryID()
{
int cat_id = 0;
cmd = new SqlCommand("SELECT category_id FROM ItemDetails.category WHERE category_desc=@cat_desc", con);
con.Open();
cmd.Parameters.AddWithValue("@cat_desc", cboCategory.Text);
reader = cmd.ExecuteReader();
while (reader.Read())
{
cat_id = int.Parse(reader["category_id"].ToString());
}
reader.Close();
con.Close();
return cat_id;
}
【问题讨论】:
-
如果它也可以工作(但来自 C#),您是否已经尝试过选择?控制连接字符串总是一件好事,如果它是正确的并且它是否按预期工作(一个没有参数的普通选择是该测试的一个不错的选择)。
-
您是否还检查了 GetCategoryID() 和 txtitemdesc.Text 是否包含值?
-
删除
AddWithValue()并添加这样的参数 -cmd.Parameters.Add("@item_desc", SqlDbType.VarChar, 1000).Value = txtitemdesc.Text; -
这张桌子上有触发器吗?可能会被违反的约束或 FK?也许甚至其他列需要此表中的值,这可能会阻止插入值?
-
如果您使用
select语句,这是正常行为,因为对于select语句,ExecuteNonQuery的返回值是-1,但由于您的问题出在Insert,因此您应该有如果您确定GetCategoryID()和txtitemdesc.Text包含值并且没有其他任何东西阻止插入这些值,则没问题。看看这个答案:stackoverflow.com/a/32736842/2946329
标签: c# sql-server executenonquery