1

我有一个名为 WorkPerUser 的表,其中包含以下列:

id  int 
username    nchar(50)
RMANumber   int
Charge  real    

“id”是自增1的主键。

我背后的代码是:

 Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSubmit.Click


        'Dim temp_id As String
        'temp_id = Session("se_userid")


        'SQL connection String and Query 

        Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
        Dim insertSql As String = "INSERT INTO [WorkPerUser] (id,username,RMANumber,Charge)" & " values (@id,@username,@rmanumber,@charge)"

        'Create SQL connection
        Dim con As New SqlConnection(connectionString)

        'Create SQl command and parameters
        Dim cmd As New SqlCommand()
        cmd.Connection = con
        cmd.CommandType = CommandType.Text
        cmd.CommandText = insertSql

        Dim id As New SqlParameter("@id", SqlDbType.Text)
        id.Value =
        cmd.Parameters.Add(id)

        Dim username As New SqlParameter("@username", SqlDbType.NChar)
        username.Value = Session("userName")
        cmd.Parameters.Add(username)

        Dim rmanumber As New SqlParameter("@rmanumber", SqlDbType.Int)
        rmanumber.Value = txtRMA.Text.ToString()
        cmd.Parameters.Add(rmanumber)

        Dim charge As New SqlParameter("@charge", SqlDbType.Real)
        charge.Value = txtCharge.Text.ToString()
        cmd.Parameters.Add(charge)

        Try
            con.Open()
            cmd.ExecuteNonQuery()
            lblMsg.Text = "Job Inserted"
        Catch ex As SqlException
            Dim errorMessage As String = "Error registering job"
            errorMessage += ex.Message

            Throw New Exception(errorMessage)
        Finally
            con.Close()
        End Try


    End Sub

正如您可能已经注意到的那样,我留下了 id.Value =空白,因为我不知道要向数据库发送什么。查询或其他地方是否需要更改任何内容?

4

1 回答 1

2

如果 Id 确实是一个自动增量(身份)列,则您不必手动插入它。只需省略 Id 部分

Dim insertSql As String = "INSERT INTO [WorkPerUser] (username,RMANumber,Charge)" & " values (@username,@rmanumber,@charge)"

您不必指定 ID。您可能想要获取最后插入的 ID。它通常是通过的SELECT SCOPE_IDENTITY(),这对于内联 SQL 来说很棘手。

检查这些链接:

于 2013-01-25T14:02:47.613 回答