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

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)

Related

System.Data.OleDb.OleDbException Error while writting query in visual basic

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\BlackHat\Documents\Travel.accdb")
Dim qry As String = "update Login set UserName='" & TextBox1.Text & "',Password='" & TextBox2.Text & "' where ID=" & Val(TextBox3.Text)
Dim cmd As New OleDbCommand(qry, con)
con.Open()
cmd.ExecuteNonQuery()
MsgBox(qry)
con.Close()
End Sub
Following error occurred in the query. the syntax and variable looks fine.
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: Syntax error in UPDATE statement.
Try this:
Dim qry As String ="update Login set UserName='" & TextBox1.Text & "',Password='" & TextBox2.Text & "' where ID=" & Val(TextBox3.Text) & ""

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 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

Bug when displaying data on a list view VB.Net with MySQL

I recently came up with a problem that wasn't there before. On the list view part of my program, it usually displays the right data. But something happened (and I tried in vain to retrace my steps but I couldn't remember touching the codes of this part), the data on the list view suddenly started not to display properly.
The recent data that I am adding aren't showing up in the list view and instead of being posted in the bottom part of the last successful data entry, it gets inserted in the beginning of the list and it only shows blanks. But whenever I click update the data is there, it just won't display properly on the list view.
Where did I go wrong? Here's my code:
Displaying of data:
Public Sub LoadPeople()
Dim sqlQuery As String = "SELECT * FROM employee_table"
Dim sqlAdapter As New MySqlDataAdapter
Dim sqlCommand As New MySqlCommand
Dim TABLE As New DataTable
Dim i As Integer
With sqlCommand
.CommandText = sqlQuery
.Connection = sConnection
End With
With sqlAdapter
.SelectCommand = sqlCommand
.Fill(TABLE)
End With
'Listview fix
ListView1.Items.Clear()
For i = 0 To TABLE.Rows.Count - 1
With ListView1
.Items.Add(TABLE.Rows(i)("id"))
With .Items(.Items.Count - 1).SubItems
.Add(TABLE.Rows(i)("emp_no"))
.Add(TABLE.Rows(i)("emp_firstnm"))
.Add(TABLE.Rows(i)("emp_midnm"))
.Add(TABLE.Rows(i)("emp_lastnm"))
.Add(TABLE.Rows(i)("dept1"))
.Add(TABLE.Rows(i)("dept2"))
.Add(TABLE.Rows(i)("position"))
.Add(TABLE.Rows(i)("schedtype"))
.Add(TABLE.Rows(i)("date_hired"))
End With
End With
Next
End Sub
Adding of data:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
If sConnection.State = ConnectionState.Closed Then
sConnection.ConnectionString = "SERVER = localhost; USERID = root; PASSWORD=; DATABASE = cph;Convert Zero Datetime=True"
sConnection.Open()
End If
Dim sqlQuery As String = "INSERT INTO employee_table(emp_no, emp_firstnm, emp_midnm, emp_lastnm, dept1, dept2, position, schedtype, date_hired) VALUES ('" & txtEmpno.Text & _
"','" & txtFname.Text & "','" & txtMname.Text & "','" & txtLname.Text & "','" & txtDept1.Text & "','" & txtDept2.Text & "','" & txtPosition.Text & "','" & txtSchedtype.Text & "','" & txtDatehired.Text & "')"
Dim sqlCommand As New MySqlCommand
With sqlCommand
.CommandText = sqlQuery
.Connection = sConnection
.ExecuteNonQuery()
End With
MsgBox("Added new record")
Dispose()
Close()
'Update
ViewRecord.LoadPeople()
End Sub

How to execute two queries at the same time in VB? (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