我在Access
上有一个数据库,我想插入2个表
我想获取主键的最后一个值(自动编号)并将其插入 req_sysino ,我坚持使用此代码,我不知道如何处理
Private Function InsertSysInvToDB(intSysInv As Integer) As Integer
Dim strSQLStatement As String = String.Empty
Dim intNoAffectedRows As Integer = 0
Dim con As New OleDb.OleDbConnection("PROVIDER = Microsoft.ace.OLEDB.12.0; Data Source = C:\Users\felmbanF\Documents\Visual Studio 2012\Projects\WebApplication3\WebApplication3\App_Data\ReportReq.accdb")
Dim cmd As OleDb.OleDbCommand
Dim reqnum As String = "Select @@REQ_NUM from ReportReq"
strSQLStatement = "INSERT INTO req_sysino (Req_num, sysinvo_ID)" +
" VALUES (" & reqnum & "','" & intSysInv & ")"
cmd = New OleDb.OleDbCommand(strSQLStatement, con)
cmd.Connection.Open()
intNoAffectedRows = cmd.ExecuteNonQuery()
cmd.Connection.Close()
Return intNoAffectedRows
End Function
这是我应该生成自动编号的插入代码
Dim dbProvider = "PROVIDER = Microsoft.ace.OLEDB.12.0;"
Dim dbSource = " Data Source = C:\Users\felmbanF\Documents\Visual Studio 2012\Projects\WebApplication3\WebApplication3\App_Data\ReportReq.accdb"
Dim sql = "INSERT INTO ReportReq (Emp_EmpID, Req_Date,Req_expecDate,Req_repnum, Req_name, Req_Descrip, Req_columns, Req_Filtes, Req_Prompts)" +
"VALUES (@reqNUM,@reqName,@reqDescrip,@reqcolumns,@reqfilters,@reqprompts)"
Using con = New OleDb.OleDbConnection(dbProvider & dbSource)
Using cmd = New OleDb.OleDbCommand(sql, con)
con.Open()
cmd.Parameters.AddWithValue("@EmpID", txtEmpID.Text)
cmd.Parameters.AddWithValue("@reqDate", DateTime.Today)
cmd.Parameters.AddWithValue("@reqExpecDate", DateTime.Parse(txtbxExpecDate.Text).ToShortDateString())
cmd.Parameters.AddWithValue("@reqNUM", txtRep_NUM.Text)
cmd.Parameters.AddWithValue("@reqName", txtRep_Name.Text)
cmd.Parameters.AddWithValue("@reqDescrip", txtbxRep_Desc.Text)
cmd.Parameters.AddWithValue("@reqcolumns", txtbxColReq.Text)
cmd.Parameters.AddWithValue("@reqfilters", txtbxFilReq.Text)
cmd.Parameters.AddWithValue("@reqprompts", txtbxPromReq.Text)
cmd.ExecuteNonQuery()
End Using
End Using
答案 0 :(得分:0)
在您ExecuteNonQuery()
INSERT INTO ReportReq ...
语句之后,您需要立即运行
SELECT @@IDENTITY
查询并检索其结果,如此
cmd.ExecuteNonQuery() ' your existing statement to run INSERT INTO ReportReq
cmd.CommandText = "SELECT @@IDENTITY"
Dim newAutoNumberValue As Integer = cmd.ExecuteScalar()