我有一个程序,将输入的细节输入到SQL Server数据库中,该程序运行良好,数据将进入SQL Server。我正在向SQL Server数据库发送customerID、customerName、CustomerAddress、CustomerAddedDate。
如何创建一条if...else语句,向用户显示一个消息框,通知他们数据插入是否成功,如果没有,原因是什么?
另外,如何让下一个可用的customerID (它是SQL Server数据库中的整数主键)自动显示在customerID文本框中?
我设想一段代码,它读取SQL Server数据库中的customerID列,然后将其加上+1,并将其设置为customerID的属性,也就是textbox1,但也许有更好的想法?
我的程序:

我的代码:
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection("Data Source=LAPTOP\\SQLEXPRESS02;Initial Catalog=Greenwich_Butcher;Integrated Security=True");
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
string dat = "Insert into [CustomerDetails](CustomerID, CustomerName, CustomerAddress, CustomerAddedDate) Values('" + Convert.ToInt32(textBox1.Text) + "','" + textBox2.Text + "','" + textBox3.Text + "','" + Convert.ToString(dateTimePicker1.Text) + "')";
SqlCommand com = new SqlCommand(dat, con);
con.Open();
int rowsAffected = com.ExecuteNonQuery();
if (rowsAffected > 0)
{
MessageBox.Show("Record inserted succesfully");
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
dateTimePicker1.Text = "";
}
else
{
MessageBox.Show("Record not inserted succesfully");
}
con.Close();
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
}发布于 2018-11-28 01:17:02
如果您创建了Customer和identity列,它将在插入记录时自动递增,但是如果假设两个人同时添加数据,您将无法知道您刚刚创建了哪一个记录。有很多不同的方法可以做到这一点,但看看你的代码,我假设你对此很陌生,所以我将给你一个简单的可行的解决方案。
你需要几样东西:
CreatedBy或类似内容的新列添加到表中。Insert查询之后执行Select查询以获得最高的CustomerId,其中CreatedBy是当前用户。这将为您提供所有数据,包括您想要的CustomerId。https://stackoverflow.com/questions/53504666
复制相似问题