我想写一个应用程序在Visual Studio C#写入基于服务的数据库。我遇到的问题是我没有收到任何错误,但是在重新启动应用程序后,没有任何内容保存到数据库中...C#基于服务的数据库不写入数据库
我知道这是因为它不允许重复主键。这几乎就像是一个临时数据库......如果是这种情况,我该如何让它成为一个持久的基于服务的数据库?
这里是我的代码:
private void button1_Click(object sender, EventArgs e)
{
try {
// Connection to DB
SqlConnection con = new SqlConnection();
con.ConnectionString = (@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\MTR_Database.mdf;Integrated Security=True");
// Insert Query
string insertquery = "INSERT INTO dbo.Job01 ([Item #], [Manufacturer], [Mill Location], [Product Description], [Weld Seam Type], [Outer Dimension], [Wall Thickness], [Coating], [Grade], [Heat], [ANSI/ASME], [Purchase Order], [Standard]) VALUES(@ItemNum, @Manufacturer, @MillLocation, @ProductDescription, @WeldSeamType, @OuterDimension, @WallThickness, @Coating, @Grade, @Heat, @ANSIASME, @PurchaseOrder, @Standard)";
SqlCommand cmd = new SqlCommand(insertquery, con);
// open connection
con.Open();
// Parameters
cmd.Parameters.AddWithValue("@ItemNum", item__TextBox.Text);
cmd.Parameters.AddWithValue("@Manufacturer", manufacturerTextBox.Text);
cmd.Parameters.AddWithValue("@MillLocation", mill_LocationTextBox.Text);
cmd.Parameters.AddWithValue("@ProductDescription", product_DescriptionTextBox.Text);
cmd.Parameters.AddWithValue("@WeldSeamType", weld_Seam_TypeTextBox.Text);
cmd.Parameters.AddWithValue("@OuterDimension", outer_DimensionTextBox.Text);
cmd.Parameters.AddWithValue("@WallThickness", wall_ThicknessTextBox.Text);
cmd.Parameters.AddWithValue("@Coating", coatingTextBox.Text);
cmd.Parameters.AddWithValue("@Grade", gradeTextBox.Text);
cmd.Parameters.AddWithValue("@Heat", heatTextBox.Text);
cmd.Parameters.AddWithValue("@ANSIASME", aNSI_ASMETextBox.Text);
cmd.Parameters.AddWithValue("@PurchaseOrder", purchase_OrderTextBox.Text);
cmd.Parameters.AddWithValue("@Standard", standardTextBox.Text);
// Execute
cmd.ExecuteNonQuery();
// close connection
con.Close();
}
catch (Exception ex)
{
// catch error
MessageBox.Show(ex.Message);
}
}
我真的不能把我的手指上正在发生的事情。
我想更多,我希望它充当SQLite ...没有一个活动的服务器,并在应用程序内。在Visual Studio中嵌入SQL Express可能吗? – Mokey
阅读此:http://stackoverflow.com/questions/6221951/sqlexception-catch-and-处理与SQL服务器的异常处理。也使用MDF的直接文件路径,看看会发生什么 –