我搜索并发现这个代码是为了将数据保存到数据库, 连接字符串是正常的, 没有例外/错误被丢弃, 但我不知道为什么这个代码没有将数据保存到我的数据库中。
string query = "Insert Into BookConfiguration (BookNum, x_axis, y_axis, BookName) Values (@BookNum, @x_axis, @y_axis, @BookName)";
string connStr = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\BookShelf.mdf;Integrated Security=True;User Instance=True";
try
{
using (SqlConnection conn = new SqlConnection(connStr))
{
SqlDataAdapter da = new SqlDataAdapter();
da.InsertCommand = new SqlCommand(query, conn);
da.InsertCommand.Parameters.Add("@BookNum", SqlDbType.Int).Value = quantity;
da.InsertCommand.Parameters.Add("@x_axis", SqlDbType.Int).Value = x;
da.InsertCommand.Parameters.Add("@y_axis", SqlDbType.Int).Value = y;
da.InsertCommand.Parameters.Add("@BookName", SqlDbType.Text).Value = openFileDialog1.FileName;
conn.Open();
da.InsertCommand.ExecuteNonQuery();
conn.Close();
}
}
catch (SqlException ex)
{
MessageBox.Show("Error Occured " + ex.Message);
}
EDIT i have now changed the code same problem
代码 :
try
{
using (TransactionScope scope = new TransactionScope())
{
using (SqlConnection conn = new SqlConnection(connStr))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.Add(new SqlParameter("@BookNum", quantity));
cmd.Parameters.Add(new SqlParameter("@x_axis", x));
cmd.Parameters.Add(new SqlParameter("@y_axis", y));
cmd.Parameters.Add(new SqlParameter("@BookName", openFileDialog1.FileName));
cmd.ExecuteNonQuery();
}
conn.Close();
}
scope.Complete();
}
}
我希望这不含糊...
代码在C# 视觉工作室 2010 sql服务器 2008...