自动增量Excel OleDb连接Vb.net
当我向excel添加新数据时,我想自动增加ID,但这些代码不会自动增加,它只是增加2,我不明白为什么请帮助p Thanksss自动增量Excel OleDb连接Vb.net,vb.net,auto-increment,Vb.net,Auto Increment,当我向excel添加新数据时,我想自动增加ID,但这些代码不会自动增加,它只是增加2,我不明白为什么请帮助p Thanksss Dim Value As Integer cn = New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + "C:\\Users\\Barbatos\\Desktop\\Book3.xlsx " + ";Extended Properties=Excel 12.0;
Dim Value As Integer
cn = New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + "C:\\Users\\Barbatos\\Desktop\\Book3.xlsx " + ";Extended Properties=Excel 12.0;")
cm = New OleDbCommand("SELECT MAX ([ID]) FROM [Sheet1$]", cn)
cn.Open()
Dim dr As OleDbDataReader = cm.ExecuteReader()
If dr.HasRows Then
dr.Read()
Value = dr(0)
Else
End If
dr.Close()
Dim str As String
Dim empid As Integer
Dim newNumber As Integer
str = "SELECT MAX([ID]) AS MAXIMUM FROM [Sheet1$]"
Dim cmd2 As OleDbCommand = New OleDbCommand(str, cn)
'Dim dr As OleDbDataReader
dr = cmd2.ExecuteReader
If dr.HasRows Then
While dr.Read()
If empid = IsDBNull(dr("MAXIMUM")) Then
newNumber = CInt(Val(empid)) + 1
End If
If newNumber = 0 Then
newNumber = 1
empid = CStr(newNumber)
ElseIf newNumber = 1 Then
newNumber = newNumber + 1
empid = CStr(newNumber)
Else
newNumber = newNumber + 1
empid = CStr(newNumber)
End If
End While
End If
dr.Close()
Me.Label2.Text = empid
解决
If dr.HasRows Then
dr.Read()
If IsDBNull(dr("MAXIMUM")) Then
empid = 1
Else
empid = CInt(dr("MAXIMUM")) + 1
End If
Else
empid = 1
End If
总结一下我的评论,我会这样做:
Dim nextId As Integer
Using connection As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Barbatos\\Desktop\\Book3.xlsx;Extended Properties=Excel 12.0;"),
command As New OleDbCommand("SELECT MAX([ID]) FROM [Sheet1$]", connection)
connection.Open()
Dim currentId = command.ExecuteScalar()
nextId = If(currentId Is DBNull.Value, 1, CInt(currentId) + 1)
End Using
或者,如果受支持,则:
Dim nextId As Integer
Using connection As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Barbatos\\Desktop\\Book3.xlsx;Extended Properties=Excel 12.0;"),
command As New OleDbCommand("SELECT ISNULL(MAX([ID]), 0) FROM [Sheet1$]", connection)
connection.Open()
nextId = CInt(command.ExecuteScalar()) + 1
End Using
如果只尝试检索单个值,则不应调用
ExecuteReader
。ExecuteScalar
方法是专门为检索单个值而存在的。我不能100%确定Excel是否支持它,但我希望如此,因此您也可以在SQL中使用ISNULL
,以保证返回一个数字:ISNULL(MAX(ID),0)如果ID
列中没有值,则将返回0。这样,就不需要在VB代码中进行额外的检查了。为什么要将字符串
文字串接在一起来创建连接字符串?将两个文本连接起来没有任何意义。如果确实要连接任何内容,请使用连接运算符(&)而不是加法运算符(+)。如果您想从变量构造连接字符串,请使用string.Format
、字符串插值或连接字符串生成器。使用IsDBNull
函数并不是特别错误,但我通常建议不要使用VB运行时函数。数据读取器有自己的IsDBNull
方法,或者您可以直接与DBNull.Value
进行比较。