由于某种原因,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;
}
答案 0 :(得分:1)
如果可能,请不要使用AddWithValue()
。实际上,当您未明确提供类型时,它将尝试隐式转换,有时隐式转换可能不是最佳转换。您可以找到更多讨论 in this link 。
最重要的是,不要忘记在分配之前清除参数,使用此行。
cmd.Parameters.Clears();
检查以下代码。
string sqlQuery = "INSERT INTO ItemDetails.item(description,category_id) VALUES (@item_desc,@cat_id)";
using (SqlCommand cmd = new SqlCommand(sqlQuery, con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.Clears(); // Add this same line in your getcategory function.
cmd.Parameters.Add("@item_desc", SqlDbType.VarChar, 1000).Value = txtitemdesc.Text;
cmd.Parameters.Add("@cat_id", SqlDbType.Int).Value = 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();
}
}