使用sqldataadapter和sqltransaction在多个表中插入记录

时间:2013-02-20 10:02:50

标签: sql vb.net

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

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

3 个答案:

答案 0 :(得分:1)

首先创建InsertCommand,然后分配事务:

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

您需要提交交易:

da.InsertCommand.Transaction.Commit()

答案 1 :(得分: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) 

答案 2 :(得分: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()