我正在添加这样的记录:
Dim pathString As String = HttpContext.Current.Request.MapPath("Banking.mdb")
Dim odbconBanking As New OleDbConnection _
("Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" + pathString)
Dim sql As String
sql = "INSERT INTO tblUsers ( FirstName, LastName, Address, City, Province, Zip, Phone, UserName, [Password])" & _
" VALUES ('" & firstName & "', '" & lastName & "', '" & address & _
"', '" & city & "', '" & province & "', '" & zip & "', '" & phone & "', '" & username & "', '" & password & "');"
odbconBanking.Open()
Dim cmd As New OleDbCommand(sql, odbconBanking)
cmd.ExecuteNonQuery()
odbconBanking.Close()
主键是名为UserID的自动编号字段。那么,我如何获得刚插入的记录的主键?
感谢。
答案 0 :(得分:5)
我相信参数化查询看起来像这样:
Dim pathString As String = HttpContext.Current.Request.MapPath("Banking.mdb")
Dim odbconBanking As New OleDbConnection _
("Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" + pathString)
Dim sql As String
sql = "INSERT INTO tblUsers ( FirstName, LastName, Address, City, Province, Zip, Phone, UserName, [Password])" & _
" VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?);"
odbconBanking.Open()
Dim cmd As New OleDbCommand(sql, odbconBanking)
//Add Params here
cmd.Parameters.Add(new OdbcParameter("@FirstName", firstName))
cmd.Parameters.Add(new OdbcParameter("@LastName", lastName))
//..etc
//End add Params here
cmd.ExecuteNonQuery()
Dim newcmd As New OleDbCommand("SELECT @@IDENTITY", odbconBanking)
uid = newcmd.ExecuteScalar
odbconBanking.Close()
我的语法可能有点偏,因为我更习惯于使用Sql Server库而不是Odbc库,但这应该让你开始。
答案 1 :(得分:4)
"SELECT @@IDENTITY"
应与Microsoft.Jet Provider一起使用。
答案 2 :(得分:2)
您需要添加
;select scope_identity();
在查询之后,并运行executeScalar以获取值。
另外,在一个完全不相关的说明中,你真的应该改变你的代码以使用参数化查询,这样你就不会被SQL注入攻击,或者由于不正确的转义字符串连接到你的sql语句而崩溃。
答案 3 :(得分:2)
知道了。以下是上述代码的外观:
Dim pathString As String = HttpContext.Current.Request.MapPath("Banking.mdb")
Dim odbconBanking As New OleDbConnection _
("Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" + pathString)
Dim sql As String
sql = "INSERT INTO tblUsers ( FirstName, LastName, Address, City, Province, Zip, Phone, UserName, [Password])" & _
" VALUES ('" & firstName & "', '" & lastName & "', '" & address & _
"', '" & city & "', '" & province & "', '" & zip & "', '" & phone & "', '" & username & "', '" & password & "');"
odbconBanking.Open()
Dim cmd As New OleDbCommand(sql, odbconBanking)
cmd.ExecuteNonQuery()
Dim newcmd As New OleDbCommand("SELECT @@IDENTITY", odbconBanking)
uid = newcmd.ExecuteScalar
odbconBanking.Close()
答案 4 :(得分:1)
最简单的方法是在代码级别生成uniqueIdentifier值,将其添加到字符串并将其发送到服务器。
Dim sql As String, _
myNewUserId as variant
myNewUserId = stGuidGen 'this function will generate a new GUID value)'
sql = "INSERT INTO tblUsers ( userId, LastName)" & _
" VALUES ('" & myNewUserId & "','" & LastName);"
您可以查看 stGuidGen guid生成代码here的提案。
这种客户端技术清晰,干净,实用