首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何添加if else语句以检查数据是否已输入SQL Server数据库并显示消息

如何添加if else语句以检查数据是否已输入SQL Server数据库并显示消息
EN

Stack Overflow用户
提问于 2018-11-28 01:03:44
回答 1查看 79关注 0票数 0

我有一个程序,将输入的细节输入到SQL Server数据库中,该程序运行良好,数据将进入SQL Server。我正在向SQL Server数据库发送customerIDcustomerNameCustomerAddressCustomerAddedDate

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

另外,如何让下一个可用的customerID (它是SQL Server数据库中的整数主键)自动显示在customerID文本框中?

我设想一段代码,它读取SQL Server数据库中的customerID列,然后将其加上+1,并将其设置为customerID的属性,也就是textbox1,但也许有更好的想法?

我的程序:

我的代码:

代码语言:javascript
复制
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();
    }
}
EN

回答 1

Stack Overflow用户

发布于 2018-11-28 01:17:02

如果您创建了Customer和identity列,它将在插入记录时自动递增,但是如果假设两个人同时添加数据,您将无法知道您刚刚创建了哪一个记录。有很多不同的方法可以做到这一点,但看看你的代码,我假设你对此很陌生,所以我将给你一个简单的可行的解决方案。

你需要几样东西:

  1. 你需要一种方法来了解使用该软件的用户。只要是独一无二的,任何东西都可以是好的。如果你没有用户登录,你可以使用计算机名(如果在域中),windows登录名。etc
  2. 将名为CreatedBy或类似内容的新列添加到表中。
  3. 现在当您插入记录时,添加您在步骤1中选择的唯一用户值
  4. Insert查询之后执行Select查询以获得最高的CustomerId,其中CreatedBy是当前用户。这将为您提供所有数据,包括您想要的CustomerId
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53504666

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档