我正在添加这样的记录:
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的自动编号字段.那么,如何获取刚插入的记录的主键?
谢谢.
我相信参数化查询看起来像这样:
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库,但这应该让你开始.