本文介绍了插入数据库mdf不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以从MDF读取数据但无法保存。我的代码如下。我在DatabaseConfig.cs中做东西并从SalesScreen.cs发送值 我尝试过: DatabaseConfig.cs:
Hi, I can read datas from MDF but cannot save. My codes are below. I do stuffs inside DatabaseConfig.cs and send values from SalesScreen.cs What I have tried: DatabaseConfig.cs:
SqlConnection connect = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\BombusDB.mdf;Integrated Security=True;"); public int buyerCheckAndSave(string buyerPhone, string buyerName, string buyerAddress, bool containsItem) { int buyerID = 0; if (containsItem) //if customer exist just find id. { connect.Open(); SqlCommand comm = new SqlCommand("SELECT TOP(1) ID FROM buyer_Tab WHERE pho LIKE @pho ORDER BY ID"); comm.Parameters.AddWithValue("@pho", '%' + buyerPhone + '%'); comm.Connection = connect; using (SqlDataReader ctr = comm.ExecuteReader()) { while (ctr.Read()) { buyerID = ctr.GetInt32(0); } } connect.Close(); return buyerID; } else //if not first save { try { connect.Open(); SqlCommand comm = new SqlCommand("INSERT INTO buyer_Tab (customer, pho, adr) VALUES ('@customer', '@pho', '@adr')"); comm.CommandType = CommandType.Text; comm.Connection = connect; comm.Parameters.AddWithValue("@customer", buyerName); comm.Parameters.AddWithValue("@pho", buyerPhone); comm.Parameters.AddWithValue("@adr", buyerAddress); comm.ExecuteNonQuery(); connect.Close(); } catch(SqlException e) { System.Windows.Forms.MessageBox.Show("Hata Olustu! \n" + e); } buyerCheckAndSave(buyerPhone, buyerName, buyerAddress, true); //after saving get id } return buyerID; }SalesScreen.cs(Winforms)
SalesScreen.cs (Winforms)
private void sellBtn_Click(object sender, EventArgs e) { billPrintDialog.Document = printBill; billPrintDialog.ShowDialog(); printBill.Print(); int customerID = 0; if (!String.IsNullOrEmpty(phoneTB.Text)) { bool containsItem = customerPhones.Any(item => item.StartsWith(phoneTB.Text)); //We have existing customers on list customerID = db.buyerCheckAndSave(phoneTB.Text, nameTB.Text, adrRTB.Text, containsItem); } MessageBox.Show(""+customerID); }推荐答案
从参数持有者中取出报价; Take the quotes off the parameter holders; SqlCommand comm = new SqlCommand("INSERT INTO buyer_Tab (customer, pho, adr) VALUES (@customer, @pho, @adr)");
更多推荐
插入数据库mdf不起作用
发布评论