2013-11-26 4 views
-2

두 쿼리를 동시에 실행하는 가장 효율적인 방법은 무엇입니까? 제출 단추를 클릭 할 때 두 개의 INSERT SQL 쿼리 (다른 테이블)를 동시에 실행하려고합니다. 그것은 가능한가?VB에서 동시에 두 개의 쿼리를 실행하는 방법은 무엇입니까? (MySql)

는 여기에 내가했던 일이야 :

Dim conn As New MySqlConnection("Server = localhost; user id = root;password = ; database = ddap_hr") 
    Dim sqlQuery1 As String = "INSERT INTO applicants VALUES ('" & lblID.Text & "' , '" & txtLName.Text & "','" & txtFName.Text & "','" & txtMName.Text & "','" & cmboGender.Text & "','" & mtxtAge.Text & "','" & dtpBdate.Value & "','" & cmboStatus.Text & "','" & txtSSS.Text & "','" & txtTin.Text & "','" & txtReligion.Text & "','" & txtAddress.Text & "','" & mtxtContactNum.Text & "','" & txtEmail.Text & "')" 
    Dim sqlQuery2 As String = "INSERT INTO appli_idgen(Lzero) VALUES ('" & lblNum.Text & "')" 
    Dim cmd1 As New MySqlCommand(sqlQuery1) 
    Dim cmd2 As New MySqlCommand(sqlQuery2) 
    Dim rdr As MySqlDataReader 

    Dim ConfirmMsg = MessageBox.Show("Are all the datas correct?" & Environment.NewLine & " • Last Name: " & txtLName.Text & Environment.NewLine & " • First Name: " & txtFName.Text & Environment.NewLine & " • Middle Name: " & txtMName.Text & Environment.NewLine & " • Gender: " & cmboGender.Text & Environment.NewLine & " • Age: " & mtxtAge.Text & Environment.NewLine & " • Date of Birth: " & dtpBdate.Text & Environment.NewLine & " • Status: " & cmboStatus.Text & Environment.NewLine & " • SSS: " & txtSSS.Text & Environment.NewLine & " • TIN: " & txtTin.Text & Environment.NewLine & " • Religion: " & txtReligion.Text & Environment.NewLine & " • Address: " & txtAddress.Text & Environment.NewLine & " • Contact Number: " & mtxtContactNum.Text & Environment.NewLine & " • E-mail: " & txtEmail.Text & Environment.NewLine, "", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1, 0, False) 

    If ConfirmMsg = MsgBoxResult.Yes Then 
     Try 
      Try 
       cmd1.Connection = conn 
       conn.Open() 
       cmd1.ExecuteNonQuery() 
       rdr = cmd.ExecuteReader 
       rdr.Read() 
      Catch ex1 As MySqlException 
       MsgBox(ex1.Message.ToString) 
      Finally 
       conn.Close() 
      End Try 

      Try 
       cmd2.Connection = conn 
       conn.Open() 
       cmd2.ExecuteNonQuery() 
       rdr = cmd.ExecuteReader 
       rdr.Read() 
      Catch ex2 As MySqlException 
       MsgBox(ex2.Message.ToString) 
      Finally 
       conn.Close() 
      End Try 
     Catch ex As MySqlException 
       MsgBox(ex.Message.ToString) 
     Finally 
      Dim addAnother = MessageBox.Show("Do you want to add another applicant?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1, 0, False) 
      If addAnother = MsgBoxResult.No Then 
       Me.Close() 
       Main_home.Refresh() 
      End If 
     End Try 

    End If 

내가 할 수 SA 많은 코드의 라인을 줄이고 자. 도움이 필요해. btw 나는 MySQL을 사용하고 있습니다. 죄송합니다. VB에서 새로 왔습니다. 미리 감사드립니다.

+0

당신의 질문은 명확하지 않고, 이번에는 더 정확하게 말하십시오. – Chelseawillrecover

+0

조언 해 주셔서 감사합니다. 나는 동시에 두 개의 다른 쿼리를 실행하고 싶다. – Potato

+0

제출 버튼을 클릭 할 때 트리거되는 코드가 있습니까? – Chelseawillrecover

답변

2

위와 같이 할.

약자로, 당신은 MySQL로 Nonquery을 실행하는 서브 루틴을 생성 한 후 어떤 트리거 (버튼, 체크 박스 등)에 배 이하를 호출 할 수

주 :이 당신이를 사용하는 방법을 알고 필요

  1. C : 당신은 그 here

    Public Sub MyNonQuery(ByVal SQCommand as String) 
         Dim conn As New MySqlConnection("server=your server ip; port=the server port; uid='your user id';password ='your password';") 
    
         Dim SQLCMD as new MySqlCommand(SQCommand, conn) 
    
         conn.open() 
         SQLCMD.ExecuteNonQuery() 
         conn.close() 
        End Sub 
    

    에 대한 자세한 찾아보실 수 있습니다 .NET에 대한 MySQL의 커넥터는 이제 다음과 같은 방식으로 (들)이 서브를 사용할 수 있습니다 ALL은 두 번

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click 
    
        MyNonQuery("Insert into db.tbl1 values(...);") 
        MyNonQuery("Insert into db.tbl2 values(...);") 
    
    End Sub 
    
  2. 단일 통화에서 보내기 두 SQL은

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click 
    
        MyNonQuery("Insert into db.tbl1 values(...); Insert into db.tbl2 values(...);") 
    
    
    End Sub 
    

제대로 SQL 주입 공격을 방지하기 위해,하지만 사용자의 데이터를 청소하는 것을 잊지 마십시오 명령. 궁극적으로 나는 당신을 공부하는 것을 제안 할 것입니다 Stored Procedures

+0

정말 고마워요. – Potato

+0

선생님,이 릴을 가지고 있습니다. 쿼리가 두 번 실행됩니다. 그리고 나는이 때문에 중복이 기본 오류있어. Pls 도움. 고맙습니다. 내 코드 : [링크] (http://puu.sh/5vyRN.txt) – Potato

+0

테이블에 기본 키가 있습니까? 이 오류는 해당 특정 테이블에 이미 존재하는 기본 키가있는 열을 삽입하려고한다는 것을 의미하기 때문입니다. –

2

질문에 답하기 위해 다른 스레드를 실행하는 두 개의 스레드를 시도해 볼 수 있습니다. 이것은 효과적으로 그들을 동시에 운영하는 것입니다.

Private Sub Button36_Click(sender As Object, e As EventArgs) Handles Button36.Click 
    Dim t1 As New Threading.Thread(AddressOf Insert1) 
    Dim t2 As New Threading.Thread(AddressOf Insert2) 
    t1.Start() 
    t2.Start() 
End Sub 

Private Sub Insert1() 
    'do insert here 
End Sub 

Private Sub Insert2() 
    'do insert here 
End Sub 

성능 향상 여부에 관계없이 의심 스럽습니다.

+0

나는 이것을 시험해 볼 것이다. 고맙습니다. – Potato

-1

이 웹 또는 Windows 기반입니까?

윈도우 형태 - 코멘트

당신이, 당신이 무엇을 시도했다 친구가 우리를 표시 한 경우 도움이 될
'Web forms 
Private Sub SubmitButton_Click(sender As Object, e As EventArgs) Handles SubmitButton.Click 
    'do insert 1 here 
    'do insert 2 here 
End Sub 
+0

이 답변은 질문 인 친구에게는 아무 것도 추가하지 않습니다. 새로운 유용한 정보를 포함하도록 편집하고 싶으십니까? –

관련 문제