我已经搜索并找到了将数据保存到数据库的代码,连接字符串是好的,并且没有抛出异常/错误,但我不知道为什么这段代码没有将数据保存到我的数据库中..
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);
}
编辑 我现在改变了代码同样的问题
代码:
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# Visual Studio 2010 sql server 2008 中编码...