c# - 如何添加 if else 语句以检查数据是否已输入 SQL Server 数据库并显示消息
问题描述
我有一个程序将输入的详细信息输入到 SQL Server 数据库中,该程序运行良好,数据将进入 SQL Server。我将customerID
, customerName
, CustomerAddress
,发送CustomerAddedDate
到 SQL Server 数据库。
如何创建一个if...else
语句以向用户显示一个消息框,以通知他们数据是否成功插入,如果没有,为什么不插入。
另外,我怎样才能自动让下一个可用的customerID
(即 SQL Server 数据库中的整数主键)自动显示在customerID
文本框中?
我想象一个从 SQL Server 数据库中的列读取的代码,customerID
然后向它添加 +1 并将其设置为customerID
aka的属性,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();
}
}
解决方案
如果您创建客户和身份列,它将在记录插入时自动增加,但如果假设 2 个人同时添加数据,您将无法知道您刚刚创建的哪一个。有很多不同的方法可以做到这一点,但看看你的代码,我认为你对此很陌生,所以我会给你一个简单的工作解决方案。
您将需要几件事:
- 您需要一种方法来了解使用该软件的用户。任何东西都可以是好的,只要它是独一无二的。如果您没有用户登录名,则可以使用计算机名(如果在域上)、Windows 登录名等内容。ETC
CreatedBy
在您的表中添加一个名为或类似的新列。- 现在,当您插入记录时,添加您在步骤 1 中选择的唯一用户值
Insert
查询后进行查询以获取当前用户Select
的最高CustomerId
位置。CreatedBy
这将为您提供所有数据,包括CustomerId
您想要的数据。
推荐阅读
- java - 如何在一个 java 活动中添加两个覆盖 onActivityResult 方法?
- laravel - Laravel:无法向登录用户发送通知
- java - 为什么在构造函数注入中有太多参数是不好的?
- javascript - Javascript 'For' 循环调试 BEGINNER
- python - 使用 Scipy 最小化返回一个 nan
- node.js - HTTP 请求与 HTTPS 请求的 API 有什么区别?
- rust - 转 Vec
进入 Vec<(&str, u64)> 获取 tui::BarChart 数据 - flutter - 颤动中带有轮播的屏幕布局
- javascript - “等待仅在异步函数中有效” discord.js
- python - if-elif-else 用于 2-dim numpy 数组