使用Ms Access在.net 2010中自动生成数字 [英] Auto generation of number in .net 2010 using Ms Access

查看:69
本文介绍了使用Ms Access在.net 2010中自动生成数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用vb.net 2010(前端)& Ms Access(2010)。我想在单击添加按钮时自动生成ID。为此,我使用了下面提到的代码



I am using vb.net 2010 (Front end) & Ms Access(2010). I want to Auto generate ID when I click on ADD button. For this I used below mentioned code

cmd.CommandText = "Select IsNull(Max(SRN)) from Employee"

 cmd.Connection = con

 rd = cmd.ExecuteReader(CommandBehavior.CloseConnection)

 If (rd.HasRows) Then

 rd.Read()

 str = Convert.ToInt32(rd(0))

 str = str + 1

 txtSRN.Text = str

 Else

 txtSRN.Text = "1"

 End If





我面临2个问题:

1. 如果(rd.HasRows)那么

对于此语句,每次系统返回TRUE而没有值在员工表中

根据逻辑,当表系统中没有值时,应在Else部分执行代码返回。

2. str =转换。 ToInt32(rd(0))

Convert.ToInt32(rd(0))此语句每次返回0值即str = 0

根据上面的代码返回 str = str + 1即0 = 0 + 1

即str = 0(当我在Employee表和amp中手动添加2条记录时;运行程序仍然系统给出相同的结果。)



I am facing 2 issues:
1. If (rd.HasRows) Then
for this statement every time system return "TRUE" whereas there is no value in Employee Table
As per the logic when there is no value in table system should execute code return in "Else" part.
2.str = Convert.ToInt32(rd(0))
"Convert.ToInt32(rd(0))" this statement every time returns "0" value i.e str=0
as per the code return above str = str + 1 i.e 0=0+1
"i.e str=0" (when I manually add 2 records in Employee table & run the program still system is giving same result.)

推荐答案

为什么选择IsNull(Max(SRN))而不是Max(SRN)?



据我所知,如果选择内的值为null,则IsNull返回。由于您在数据库中有记录,因此将返回false。转换为整数的False始终为0,因此您总是尝试插入值1.



您应该只选择Max(SRN),删除IsNull part。
Why are you selecting IsNull(Max(SRN)) instead of just Max(SRN)?

As far as I know, IsNull returns if the value is null inside the selection. Since you have records in the database this will return false. False converted to an integer is always 0, so you are always trying to insert the value of 1.

You should be just selecting Max(SRN), removing the IsNull part.


这是你在代码中没有做的事情。设置数据库以自动生成ID。



为什么?因为并发。如果您的应用程序的两个副本正在运行并且它们同时执行查询怎么办?它们都会生成相同的ID,使ID列无效并具有重复的条目。设置数据库引擎是为了防止这种情况发生,但前提是它正在生成ID号序列。
This is something you do NOT do in your code. Setup your database to autogenerate the ID's.

Why? Because of concurrency. What if two copies of your application are running and they both execute the query at the same time?? They will both generate the same ID, invalidating your ID column with duplicate entries. The database engine is setup to prevent this from happening, but only if it is generating the ID number sequence.


这篇关于使用Ms Access在.net 2010中自动生成数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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