在一行中执行两个cmd.commandtext

时间:2015-10-21 17:27:40

标签: vb.net cmd

程序一次执行一个cmd.commandtext。我的两个表都使用相同的主键ID。

如何同时执行两个cmd.commandtext?

Imports System.Data
Imports System.Data.OleDb

Public Class Form1
Dim cnnOLEDB As New OleDbConnection
Dim cmdInsert As New OleDbCommand
Dim cmdOLEDB As New OleDbCommand
Dim cmdUpdate As New OleDbCommand
Dim connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data    Source=C:\Users\Harry\Documents\Database1.accdb;"

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    cnnOLEDB.ConnectionString = connection
    cnnOLEDB.Open()
End Sub

Private Sub btnReal_Click(sender As Object, e As EventArgs) Handles btnReal.Click
    If txtName.Text <> "" And txtId.Text <> "" And txtReceipt.Text <> "" Then

        cmdUpdate.CommandText = "UPDATE customer Set Stu_Name = '" & txtName.Text & " '   " & "WHERE ID = " & txtId.Text & " ;  "

        cmdUpdate.CommandText = "UPDATE admin Set receipt = '" & txtReceipt.Text & " '   " & "WHERE ID = " & txtId.Text & " ;  "

        cmdUpdate.CommandType = CommandType.Text
        cmdUpdate.Connection = cnnOLEDB
        cmdUpdate.ExecuteNonQuery()

        cmdUpdate.Dispose()

        MsgBox(txtName.Text + "Record Updated!")

    End If
End Sub

1 个答案:

答案 0 :(得分:3)

这里要说的第一件事是:不要使用字符串连接来构建SQL查询,但始终使用参数化查询。没有它你会发现很多问题,比如解析你名字中的单引号或者最糟糕的是Sql Injection hack。说,我想你正在使用OleDb(可能与Access数据库)。此方案不支持在单个sql语句中执行多个命令 更改命令文本

后,您被迫调用ExecuteNonQuery两次
Private Sub btnReal_Click(sender As Object, e As EventArgs) Handles btnReal.Click
    If txtName.Text <> "" And txtId.Text <> "" And txtReceipt.Text <> "" Then
        cmdUpdate.Connection = cnnOLEDB
        cmdUpdate.CommandText = "UPDATE customer Set Stu_Name = @name " & _
                                "WHERE ID = @id"
        cmdUpdate.Parameters.Add("@name", OleDbType.VarWChar).Value =  txtName.Text 
        cmdUpdate.Parameters.Add("@id", OleDbType.Integer).Value = Convert.ToInt32(txtId.Text)
        cmdUpdate.ExecuteNonQuery()

        cmdUpdate.Parameters.Clear()
        cmdUpdate.CommandText = "UPDATE admin Set receipt = @recpt " & _ 
                                "WHERE ID = @id"
        cmdUpdate.Parameters.Add("@recpt", OleDbType.VarWChar).Value =  txtReceipt.Text 
        cmdUpdate.Parameters.Add("@id", OleDbType.Integer).Value = Convert.ToInt32(txtId.Text)
        cmdUpdate.ExecuteNonQuery()
    End If
End Sub

与您的实际问题并不严格相关,但从您的代码中可以清楚地看出,您拥有全局连接对象以及全局命令对象。不要这样做。您在性能方面获得的收益很少,但是在处理连接时会遇到问题,跟踪打开/关闭状态,您将消耗宝贵的系统资源。始终在using语句中使用本地连接对象。