How to execute two queries at the same time in VB? (MySql) - mysql

What's the most efficient way to execute two queries at the same time?
I want to execute two INSERT sql queries (different tables) simultaneously when I click the submit button. is it possible?
Here's what I did:
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
I want to reduce the line of codes as much sa possible. I need your help. btw I'm using MySql. Sorry cause I'm new in VB. Thanks in advance.

It would help if you've shown us what you've tried, friend.
As it stands, you can create a subroutine which will execute Nonquery to MySQL then CALL that sub TWICE on any trigger(button, checkbox, etc.):
Note: this requires you know how to use the MySQL connector for .NET You can look for more on that 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
Now you can use this sub in the following manner(s):
CALL it twice
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
On a single call, Send TWO SQL commands
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
Remember to properly Clean the data from the user though, to prevent SQL Injection attacks. Ultimately I would suggest you look into studying Stored Procedures

To answer the question you could try and start two threads running one immeddiately after the other. This is effectively having them run at the same time.
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
Whether you will get any performance improvement I doubt.

im late but try this, hope it helps
Public Sub CreateCommand(ByVal connectionString As String)
Using connection As New SqlConnection(connectionString)
Dim query As String = "INSERT INTO tbl_example ..."
Dim query2 As String = "INSERT INTO tbl_add ..."
Dim QueryString As String = String.Concat(query,";",query2)
Dim command As New SqlCommand(QueryString, connection)
command.Connection.Open()
command.ExecuteNonQuery()
End Using
End Sub

Is this web or windows based?
Windows forms - do as above comment
'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

Related

Handling exceptions thrown by MySQL database on duplicate primary key

How to have an error handler that when I enter an ID in the text box and that ID is already existed in the database it will say. "ID already existed"
Here is my code
Public Class frmPawn
Dim ds As DataSet
Dim da As MySqlDataAdapter
Dim cmd As New MySqlCommand
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim con As New MySqlConnection("host=localhost; username=root; password=; database=pawnshop")
con.Open()
cmd.Connection = con
ds = New DataSet
da = New MySqlDataAdapter("insert into clients (clientid, fname, mname, lname, address, city, prov, zip, contact, birth, sex) values('" & txtId.Text & "','" & txtFname.Text & "','" & txtMname.Text & "','" & txtLname.Text & "','" & txtAddress.Text & "','" & txtCity.Text & "','" & txtProv.Text & "','" & txtZip.Text & "','" & txtContact.Text & "','" & DateTimePicker_DOB.Text & "','" & lblSex.Text & "')", con)
da.Fill(ds, "clients")
End Sub
End Class
I will not discuss how you should really design your system. But here is what you directly asked for
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
' your code here
Catch mySqlEx As MySqlExeption
' Here handle MySql Exceptions
If mySqlEx.Number = 1068 Then
. . . . .
' Exception number reference:
' http://dev.mysql.com/doc/refman/5.6/en/error-messages-server.html
Catch ex As Exception
' Here handle any other Exceptions
End Try
End Sub
As you see, you can use MySql for .Net documentation to get all the exception info, which you then handle in your code. The error you receive, I believe the code is 1068. Once you have this code running, you can put break point and check, what the code you receiving and then handle it.
You Can try to select a row from your databse with that said ID, if anything is selected than it already exists, otherwise you can run your code.

Inserting Data on mysql and vb.net

I've got a table name stocks with following Columns :
ItemID, Item, Serial, Quantity, Category, Class, Unit, Beg_Date
and this is what I coded on vb.net:
Private Sub Savebtn_Click(sender As Object, e As EventArgs) Handles Savebtn.Click
Try
If txtItemID.Text = "" Or txtItemName.Text = "" Or txtQuantity.Text = "" Or cBoxCategory.Text = "" Or cBoxClass.Text = "" Or cBoxUnit.Text = "" Or dtpAdd.Value =""Then
MsgBox("All fields required!")
Else
ConStr.Open()
Dim Add_Query As String
Add_Query = "INSERT INTO Stocks (ItemID,Item,Serial,Quantity,Category,Class,Unit,Beg_Date) VALUES ('" & txtItemID.Text & "','" & txtItemName.Text & "','" & txtSerial.Text & "','" & txtQuantity.Text & "','" & cBoxCategory.Text & "','" & cBoxClass.Text & "','" & cBoxUnit.Text & "','" & dtpAdd.Value & "')"
Cmd = New MySqlCommand(Add_Query, ConStr)
Rdr = Cmd.ExecuteReader
MsgBox("Successfully Added!")
Me.Hide()
ConStr.Close()
End If
Catch ex As MySqlException
MsgBox("Connection Failed!")
Finally
ConStr.Dispose()
End Try
End Sub
Everytime I save the data when user input values it always give me a
Mysqlexception error "Connection Failed!"..
Any Idea how to fix this?
Make sure you have closed all previous connections. Add the line
If(ConStr != ConnectionState.Open)
before opening the connection again
This will check for the connection being open before you try to open it again.
For the Catch, use
MsgBox("Connection Failed!" & Ex.Message)
to show the actual exception being thrown.
Also, unless you need to return records, using
Cmd.ExecuteNonQuery()
is preferred method to run an action query.

Inserting query results from MS SQL 2008 to MYSQL via VB2010

Im a newbie in VB2010 & in MYSQL Database.
I have 2 database one on MS SQL 2008 (BigData) and another on Mysql. I have written some code in VB2010 to fetch data from SQL2008 and insert into MySQL. My goal is to transfer all data from MS SQL to MySQL as quick as I can thats why I created a simple vb script that will act as middleware to transfer data from MS SQL to MySQL.
My Headache is, almost 1 hour to transfer the 28,000 records from MS SQL to MySQL database. Is there any easiest way to transfer the data or I need to enhance my VBScript program. Please help to improve my VBScript below.
Thank you in advance.
Imports MySql.Data.MySqlClient
Imports System.Data
Imports System.Data.SqlClient
Public Class Form1
Dim SQLConnectionSQL As MySqlConnection = New MySqlConnection
Dim connectionStringSQL As String = "Data Source=solomon;Initial Catalog=testapp;Persist Security Info=True;User ID=sa;Password=Passw0rd"
Dim connectionString As String = "Server=192.168.1.199; User Id=gil; Password=Passw0rd; Database=testapp"
Dim SQLConnection As MySqlConnection = New MySqlConnection
Dim oDt_sched As New DataTable()
Private Sub btnRetrieve_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRetrieve.Click
Dim con_Solomon As String
Dim connection As SqlConnection
Dim command As SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet
Dim sql As String
Dim str_carSql As String
lblCounter.Text = 0
con_Solomon = "Data Source=solomon;Initial Catalog=MARYLANDAPP;Persist Security Info=True;User ID=sa;Password=Passw0rd"
sql = "SELECT LTRIM(RTRIM(DocType)) as DocType, LTRIM(RTRIM(cust_classID)) as cust_classID, LTRIM(RTRIM(salesman)) as salesman, LTRIM(RTRIM(CustId)) as CustId, LTRIM(RTRIM(name)) as name, LTRIM(RTRIM(ClassID)) as ClassID, LTRIM(RTRIM(invoice_no)) AS refnbr, invoice_delv_date AS Delv_DocDate, Age, AR_Amount, LTRIM(RTRIM(STATUS)) as STATUS, LTRIM(RTRIM(AGE_GROUP)) as AGE_GROUP, LTRIM(RTRIM(company)) AS comp, '' AS Deposit_Date, Credit_Limit, LTRIM(RTRIM(Terms)) as Terms, LTRIM(RTRIM(customer_name)) AS ShipName, LTRIM(RTRIM(PO_Number)) as PO_Number, LTRIM(RTRIM(Kob)) as Kob, LTRIM(RTRIM(check_date)) as check_date FROM a_aging_ardoc_report"
connection = New SqlConnection(con_Solomon)
Try
connection.Open()
command = New SqlCommand(sql, connection)
command.CommandTimeout = 420
adapter.SelectCommand = command
adapter.Fill(ds, "PO_Monitoring")
adapter.Dispose()
command.Dispose()
connection.Close()
''****** MYSQL CONNECTION *****
SQLConnection = New MySqlConnection()
SQLConnection.ConnectionString = connectionString
SQLConnection.Open()
Dim sqlCommand As New MySqlCommand
Dim delv_docdate, check_date
For a = 0 To ds.Tables(0).Rows.Count - 1
With ds.Tables(0).Rows(a)
If Not IsDBNull(.Item(7)) Then
delv_docdate = .Item(7)
Else
delv_docdate = ""
End If
If Not IsDBNull(.Item(19)) Then
check_date = .Item(19)
Else
check_date = ""
End If
str_carSql = "insert into agingreportsummary(doctype,cust_classid,salesman,custId,name,classid,refnbr,delv_docdate,age,ar_amount,status,age_group,comp,credit_limit,terms,shipname,po_number,kob,check_date) " & _
"VALUES('" & .Item(0) & "','" & .Item(1) & "','" & Replace(.Item(2), "'", "") & "','" & .Item(3) & "','" & Replace(.Item(4), "'", "") & "','" & Replace(.Item(5), "'", "") & "','" & .Item(6) & "','" & delv_docdate & "'," & Replace(.Item(8), ",", "") & "," & Replace(.Item(9), ",", "") & ",'" & Replace(.Item(10), "'", "") & "','" & .Item(11) & "','" & .Item(12) & "','" & .Item(14) & "','" & .Item(15) & "','" & Replace(.Item(16), "'", "") & "','" & Replace(.Item(17), "'", "") & "','" & .Item(18) & "','" & check_date & "');"
End With
sqlCommand.Connection = SQLConnection
sqlCommand.CommandText = str_carSql
sqlCommand.ExecuteNonQuery()
Next a
SQLConnection.Close()
MsgBox("Finish")
Catch ex As Exception
MsgBox(str_carSql)
MsgBox(ex.Message)
End Try
End Sub
End Class
You can try using a parameterised query instead of building a query for each row. That should improve things slightly since the statement wouldn't need to be prepared every time.
Add all the required parameters to the command.
Set the command text once, and change it to use parameters.
Inside the loop you would only set the parameter values and call the executenonquery method
This would have the added benefit of not being vulnerable to sql injection.
Hope that helps

How to save vb.net combobox content into mysql table?

I have an issue here .. i cant save combobox content into my table ... all other data are successfully saved but the combo box is saved either 1 or zero .. what seems to be wrong?
My tables are designed through navicat .. does this have anything to do with my choice of data type? knowing that I chose the data type to be Text
This is my code and it shows no run errors
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim conStr As String = ("Data Source=localhost;user id=root;password=123456;database=sam;")
Try
Dim con As New MySqlConnection(conStr)
Dim cmd As MySqlCommand
For i = 0 To ComboBox4.Items.Count
con.Open()
Dim sqls As String = "INSERT INTO initial_nom(f_name,s_name,th_name,fo_name,app_no,adm_type) VALUES('" & TextBox1.Text & "', '" & TextBox2.Text & "', '" & TextBox3.Text & "', '" & TextBox4.Text & "'," & TextBox5.Text & ",'" & ComboBox4.SelectedIndex.ToString & "')"
cmd = New MySqlCommand(sqls, con)
cmd.ExecuteNonQuery()
Next
Catch ex As Exception
MsgBox("Error in saving to Database. Error is :" & ex.Message)
End Try
End Sub
SelectedIndex is integer which point to index of the selected item. Assuming that combobox's data source contains collection of string, try to use SelectedItem instead, type-cast it to string :
DirectCast(ComboBox4.SelectedItem, String)

VB with SQL Connection

I get an error when I try to connect to my database.
What I want to do is to check if I have on the same row from my DataBase a name and a surname
ex. Id_ 1 Michael Dawn
I have 2 textboxes and If they include:
Textbox1 - Michael
Textbox2 - Dawn
Then it's a positive match
I get an error :
Need some help with this one guys, thanks
Here is my code
Imports MySql.Data
Imports MySql.Data.MySqlClient
Public Class Form2
Dim dbCon As MySqlConnection
Dim strQuery As String = ""
Dim SQLCmd As MySqlCommand
Dim DR As MySqlDataReader
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'just a message
MsgBox(" You are searching for the users: " & vbCrLf & "Name: " & TextBox1.Text & vbCrLf & "Surname: " & TextBox2.Text)
' connecting to the database
dbCon = New MySqlConnection("Server = localhost, Database = users, Uid = root, Pwd = password")
strQuery = "SELECT users.name, users.surname" & _
"WHERE users.name = '" + TextBox1.Text + "'AND password = '" + TextBox2.Text + "'"
SQLCmd = New MySqlCommand(strQuery, dbCon)
'Database open
Try
dbCon.Open()
DR = SQLCmd.ExecuteReader
If DR.HasRows = 0 Then
MsgBox("Not a match", MsgBoxStyle.Critical)
Else
MsgBox("You guessed the correct name: " & TextBox1.Text & "and the surname: " & TextBox2.Text)
End If
'Close
DR.Close()
dbCon.Close()
Catch ex As Exception
MsgBox("Failure to communicate " & vbCrLf & vbCrLf & ex.Message)
End Try
End Sub
End Class