如何使用c#&获取sql数据库中特定列的最后一行值将其显示在文本框中 [英] How to obtain the last row value of a particular column in the sql database using c# & display it in textbox

查看:388
本文介绍了如何使用c#&获取sql数据库中特定列的最后一行值将其显示在文本框中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好每个人......我刚开始进行C#编程

问题场景 -

我在SQL DB中采用了一个表维护信息。 &安培;已将主键分配给ID列。通过C#添加数据时我想添加'当前Id值+ 1'和&将其显示在维护ID TextBox中。这意味着如果存储了4条记录,那么在插入下一条记录时,维护ID应为5。



p.s.在添加信息时我已禁用此文本框以避免手动输入ID




我尝试过:



public void autoID()

{

con.Open();

string query =SELECT MAX(MaintenanceID)FROM MaintenanceInfo;

SqlCommand cmd = new SqlCommand(query,con);

int ID =(int)cmd.ExecuteScalar( );

ID = ID + 1;

tbMaintID.Text = ID.ToString();

con.Close();

//使用此代码显示错误连接仍然打开.....



}

private void MaintenanceDetails_Load(object sender,EventArgs e)

{

autoID();

}

解决方案

不要。

这是一种非常危险的做事方式。

相反,使用IDENTITY字段在您的数据库中让SQL为您整理值。获得最大值并自行递增的问题在于它在开发中工作正常,但是一旦开始生产就会产生间歇性问题,因为两个或更多用户最终会尝试使用相同的ID值。



请参阅:身份栏 - 维基百科,免费的百科全书 [ ^ ],此处: SQL自动递增字段 [ ^ ]

hello every one ...I've just started C# programming
problem scenario-
I've taken a table MaintenanceInfo in SQL DB. & assigned primary key to 'ID' column. while adding data through C# I want to add the 'current Id value + 1' & display it into Maintenance ID TextBox. that means if there are 4 records stored then while inserting next record the Maintenance ID should be 5 .

p.s. while adding info I've disabled this Textbox to avoid manual entry as a ID


What I have tried:

public void autoID()
{
con.Open();
string query = "SELECT MAX(MaintenanceID) FROM MaintenanceInfo";
SqlCommand cmd = new SqlCommand(query, con);
int ID = (int)cmd.ExecuteScalar();
ID = ID + 1;
tbMaintID.Text = ID.ToString();
con.Close();
//with this code it shows error -connection still open.....

}
private void MaintenanceDetails_Load(object sender, EventArgs e)
{
autoID();
}

解决方案

Don't.
That's a very dangerous way to do things.
Instead, use an IDENTITY field in your database and let SQL sort out the value for you. The problem with getting the maximum and incrementing it yourself is that it works fine in development, but as soon as you get to production it gives intermittent problems because two or more users end up trying to use the same ID value.

See here: Identity column - Wikipedia, the free encyclopedia[^] and here: SQL AUTO INCREMENT a Field[^]


这篇关于如何使用c#&获取sql数据库中特定列的最后一行值将其显示在文本框中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆