0

对我有用的解决方案是:

         sqlstr = "declare "
            sqlstr &= "@returnId int "
            sqlstr &= " BEGIN TRANSACTION " & _
                    " INSERT INTO sales ([user_name],[password],[full_Name],[email]) " & _
                    " VALUES (@user_name,@password,@full_Name,@email) " & _
                    " set @returnId = (select SCOPE_IDENTITY()) " & _
                    " INSERT INTO Sales_trade ([id_s],[trade]) " & _
                    " VALUES (@returnId,@trade) " & _
                    "IF (@@error <> 0) " & _
                    " ROLLBACK TRANSACTION " & _
                    " ELSE COMMIT TRANSACTION "

            cmd = New SqlCommand(sqlstr, myConn)
            Dim par1 As New SqlParameter
            par1.ParameterName = "@user_name"
            par1.Value = unam
            cmd.Parameters.Add(par1)

            'Do the same for all other parameters

            cmd.ExecuteNonQuery()

    myConn.Close()

这就是它对我的工作方式,我为参数(par1)所做的代码对于其余部分都是相同的。

4

1 回答 1

1

最初,我建议您将查询参数化以避免 sql 注入。创建一个事务并使用类似上面的 sql 语句:

sqlstr = " BEGIN TRANSACTION " & _
" INSERT INTO sales ([user_name],[password],[full_Name],[email]) " & _
" VALUES (@user_name,@password,@full_Name,@email) " & _
" set @returnId = (select SCOPE_IDENTITY()) " & _
" INSERT INTO Sales_trade ([id_s],[trade]) " & _
" VALUES (@returnId,@trade) " & _
"IF (@@error <> 0) " & _
" ROLLBACK TRANSACTION " & _
" ELSE COMMIT TRANSACTION "
dim par as new SqlParameter
par.Name = "@user_name"
par.Value = "test"
.... do this for all parameters
cmd.Parameters.Add(par)
于 2013-08-06T08:57:41.203 回答