0

我正在尝试使用 sqldataadapter 和 sqltransaction 一次在多个表中插入记录。我使用以下代码。但它不工作。请帮帮我.......告诉我这段代码中的问题

Dim cn As New SqlConnection("Data Source=.\SQLEXPRESS;Initial Catalog=AMHSDB;Integrated Security=True")
Dim da As New SqlDataAdapter
Dim ds As New DataSet
Dim trans As SqlTransaction
Dim tot As Integer
Public Sub RecordSave()
    tot = CInt(TB3.Text.Trim) + CInt(TB4.Text.Trim) + CInt(TB5.Text.Trim) + CInt(TB6.Text.Trim)
    Dim yr As String
    yr = Now.Year()
    Try
        cn.Open()
        trans = cn.BeginTransaction()
        da.InsertCommand.Transaction = trans
        da.InsertCommand = New SqlCommand("INSERT INTO[FTUT_tbl] (roll_no,s_name,class,session,eng_i,ben,math,stu_wor,gra_tot) VALUES ('" & TB1.Text.Trim & "','" & TB2.Text.Trim & "','Nursery','" & yr & "','" & TB3.Text.Trim & "','" & TB4.Text.Trim & "','" & TB5.Text.Trim & "','" & TB6.Text.Trim & "','" & tot & "')", cn)
        da.InsertCommand.ExecuteNonQuery()
        da.Dispose()
        da.InsertCommand = New SqlCommand("INSERT INTO[FTE_tbl] (roll_no,s_name,class,session) VALUES ('" & TB1.Text.Trim & "','" & TB2.Text.Trim & "','Nursery','" & yr & "')", cn)
        da.InsertCommand.ExecuteNonQuery()
        da.Dispose()
trans.Commit()
        MsgBox("Rocord Successfully Inserted!")
    Catch ex As Exception
        trans.Rollback()
        MsgBox(ex.Message)
    Finally
        cn.Close()
    End Try
End Sub
4

3 回答 3

1

创建第InsertCommand一个,然后分配事务:

da.InsertCommand = New SqlCommand("...")
da.InsertCommand.Transaction = trans

你需要提交你的交易:

da.InsertCommand.Transaction.Commit()
于 2013-02-20T10:07:32.213 回答
0

你的问题是你在第一次插入中处理了 sql 命令,但是你没有在另一个插入中再次打开它。

试试这个.....

cn.Open()
    trans = cn.BeginTransaction()
    da.InsertCommand.Transaction = trans
    da.InsertCommand = New SqlCommand("INSERT INTO[FTUT_tbl] (roll_no,s_name,class,session,eng_i,ben,math,stu_wor,gra_tot) VALUES ('" & TB1.Text.Trim & "','" & TB2.Text.Trim & "','Nursery','" & yr & "','" & TB3.Text.Trim & "','" & TB4.Text.Trim & "','" & TB5.Text.Trim & "','" & TB6.Text.Trim & "','" & tot & "')", cn)
    da.InsertCommand.ExecuteNonQuery()
    da.Dispose()
    cn.Open()
    da.InsertCommand = New SqlCommand("INSERT INTO[FTE_tbl] (roll_no,s_name,class,session) VALUES ('" & TB1.Text.Trim & "','" & TB2.Text.Trim & "','Nursery','" & yr & "')", cn)
    da.InsertCommand.ExecuteNonQuery()
    da.Dispose()
于 2014-02-01T01:28:17.313 回答
0

试试这个,可能对你有帮助

 Dim dsBillMst As DataTable
 Dim TrDtsSvr As SqlTransaction
 Dim cmdReadLocal As New SqlCommand
 Dim ConSvr As New SqlConnection(gblstrDBConnectionStr)
 ConSvr.Open()
 TrDtsSvr = ConSvr.BeginTransaction() 
 cmdReadLocal.Transaction = TrDtsSvr 
 cmdReadLocal.commandtext="//your insert statement"
 cmdReadLocal.executenonquery()
 adapter = New SqlDataAdapter(cmdReadLocal)
            dsBillMst = New DataTable
            adapter.Fill(dsBillMst) 
于 2013-02-20T10:51:49.800 回答