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

Getting primary key after an insert in asp.net (visual basic)(在 asp.net 中插入后获取主键(visual basic))
本文介绍了在 asp.net 中插入后获取主键(visual basic)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在添加这样的记录:

I'm adding a record like this:

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

The primary key is an autonumber field called UserID. So, how do I get the primary key of the record I just inserted?

谢谢.

推荐答案

我相信参数化查询应该是这样的:

I believe a parameterized query would look something like this:

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 库,但这应该可以帮助您入门.

My syntax might be a bit off as I am more accustomed to using the Sql Server library and not the Odbc library, but that should get you started.

这篇关于在 asp.net 中插入后获取主键(visual basic)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Setup RabbitMQ consumer in ASP.NET Core application(在 ASP.NET Core 应用程序中设置 RabbitMQ 消费者)
Adding Custom header to the excel file(将自定义标题添加到 excel 文件)
ASP.NET masterpages: how to insert markup in the head section inside the aspx?(ASP.NET 母版页:如何在 aspx 内的 head 部分插入标记?)
Cache-Control Headers in ASP.NET(ASP.NET 中的缓存控制标头)
Could not load file or assembly #39;Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed#39;(无法加载文件或程序集“Newtonsoft.Json,版本=4.5.0.0,文化=中性,PublicKeyToken=30ad4fe6b2a6aeed) - IT屋-程序员软件开
Specifying a custom DateTime format when serializing with Json.Net(使用 Json.Net 序列化时指定自定义 DateTime 格式)