当前位置:  开发笔记 > 编程语言 > 正文

在asp.net中插入后获取主键(visual basic)

如何解决《在asp.net中插入后获取主键(visualbasic)》经验,为你挑选了1个好方法。

我正在添加这样的记录:

    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的自动编号字段.那么,如何获取刚插入的记录的主键?

谢谢.



1> Chad Braun-D..:

我相信参数化查询看起来像这样:

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库,但这应该让你开始.

推荐阅读
携手相约幸福
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有