首页 > 解决方案 > 如何添加 if else 语句以检查数据是否已输入 SQL Server 数据库并显示消息

问题描述

我有一个程序将输入的详细信息输入到 SQL Server 数据库中,该程序运行良好,数据将进入 SQL Server。我将customerID, customerName, CustomerAddress,发送CustomerAddedDate到 SQL Server 数据库。

如何创建一个if...else语句以向用户显示一个消息框,以通知他们数据是否成功插入,如果没有,为什么不插入。

另外,我怎样才能自动让下一个可用的customerID(即 SQL Server 数据库中的整数主键)自动显示在customerID文本框中?

我想象一个从 SQL Server 数据库中的列读取的代码,customerID然后向它添加 +1 并将其设置为customerIDaka的属性,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();
    }
}

标签: c#sql-servervisual-studio

解决方案


如果您创建客户和身份列,它将在记录插入时自动增加,但如果假设 2 个人同时添加数据,您将无法知道您刚刚创建的哪一个。有很多不同的方法可以做到这一点,但看看你的代码,我认为你对此很陌生,所以我会给你一个简单的工作解决方案。

您将需要几件事:

  1. 您需要一种方法来了解使用该软件的用户。任何东西都可以是好的,只要它是独一无二的。如果您没有用户登录名,则可以使用计算机名(如果在域上)、Windows 登录名等内容。ETC
  2. CreatedBy在您的表中添加一个名为或类似的新列。
  3. 现在,当您插入记录时,添加您在步骤 1 中选择的唯一用户值
  4. Insert查询后进行查询以获取当前用户Select的最高CustomerId位置。CreatedBy这将为您提供所有数据,包括CustomerId您想要的数据。

推荐阅读