Inserting Data on mysql and vb.net - mysql

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.

Related

Why do I get this kind of error "System.MissingMemberException: 'Public member 'Text' on type 'String' not found.'" in VB.Net

I'm trying to insert data to MySql using vb.net. When I try to insert I've got the error. Please Help me.
Private Sub addEmp_Click(sender As Object, e As EventArgs) Handles addEmp.Click
MysqlConn = New MySqlConnection
MysqlConn.ConnectionString =
"server=localhost;userid=root;password=;database=vbdb"
Dim READER As MySqlDataReader
Dim birthDate As String = bDay.Value.ToString("yyyy/mm/dd")
Dim dateHired As String = dHired.Value.ToString("yyyy/mm/dd")
Try
MysqlConn.Open()
Dim Query As String
Query = "insert into vbdb.employee_info (Last_Name, First_Name, Middle_Name, Gender, Birthdate, Address, Contact, Position, Emp_Type, Email, Date_Hired) values ('" & firstName.Text & "','" & lastName.Text & "','" & middleName.Text & "','" & gender.Text & "','" & birthDate & "','" & gender.Text & "','" & address.Text & "','" & contact.Text & "','" & position.SelectedItem.Text & "','" & type.SelectedItem.Text & "','" & email.Text & "','" & dateHired & "')"
COMMAND = New MySqlCommand(Query, MysqlConn)
READER = Command.ExecuteReader
MessageBox.Show("Data Saved")
MysqlConn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
End Try
End Sub
You're using position.SelectedItem.Text. Presumably position is a ComboBox or ListBox and you have bound it to some list. Presumably the property or column that you have specified via the ValueMember contains Strings. That means that position.SelectedItem is a String and you are trying to access a Text member that doesn't exist.
For one thing, you should turn Option Strict On. That code wouldn't even compile then. That would mean that, if position.SelectedItem is a String, you would have to cast it as that type, probably using CStr. If it wasn't already obvious that you already had the String you needed, the compiler would tell you without your having to run the project that type String had no Text property.

vb.net, mysql inserting dates

hi im trying to insert dates from vb.net into my sql database and the results keep showing as 00-00-00 i use a date time picker to get the date which is formated to short
Public Sub NewAppointment()
SQLCommand.Connection = SQLconnection
SQLCommand.CommandText = "INSERT INTO " & _
appointment(TattooID,Date,Time,Length,Deposit,Cost) VALUES"& _
('" & _Tattoo.ID & "','"& _
" & AppDate.Date & "','" & _
" & AppTime & "','" & _
" & AppLength.ToString & "','" & _
" & AppDespoit & "','" & AppCost & "');"
SQLCommand.CommandType = CommandType.TableDirect
Try
SQLconnection.Open()
SQLCommand.ExecuteNonQuery()
SQLconnection.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
SQLconnection.Dispose()
End Sub
As usual these problems (and other as well) are totally avoided with a parameterized query
This is an example, you need to fix the correct datatype (MySqlDbType) for each parameter to match the datatype of your datatable fields
SQLCommand.Connection = SQLconnection
SQLCommand.CommandText = "INSERT INTO " & _
" appointment(TattooID,Date,Time,Length,Deposit,Cost) VALUES "& _
" (#id, #appDate, #AppTime, #AppLength,#AppDespoit,#AppCost);"
SQLCommand.Parameters.Add("#id", MySqlDbType.VarChar).Value = _Tattoo.ID
SQLCommand.Parameters.Add("#AppDate", MySqlDbType.Date).Value = AppDate.Date
SQLCommand.Parameters.Add("#AppTime", MySqlDbType.Date).Value = AppTime
SQLCommand.Parameters.Add("#AppLength", MySqlDbType.VarChar).Value = AppLength
SQLCommand.Parameters.Add("#AppDespoit", MySqlDbType.VarChar).Value = AppDespoit
SQLCommand.Parameters.Add("#AppCost", MySqlDbType.VarChar).Value = AppCost
Now, the job to get a correct value for your date field is passed to the database engine that receives a parameter of type Date and knows how to extract the value from the parameter and store it in the relative field.
Notice how your query is now more readable and, as an added benefit, you avoid any possible Sql Injection

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

getting the id of record added to mysql db

Hoping someone can help me out with this.
I've made an app linked to a mysql db.
I'm writing details of remote hosts to a database at the minute.
I'm saving remote credentials too, but in a different table.
I have a colomn in my 'credentials' table called 'hosts_linked_id' which i want to contain the id of the parent record in the 'hosts' table.
Here is my code so far...
SQLConnection.ConnectionString = connectionstring
Try
If SQLConnection.State = ConnectionState.Closed Then
SQLConnection.Open()
Dim SQLStatement As String = "INSERT INTO hosts(name, description, host, type, port) VALUES('" & txtname.Text & "','" & txtdescription.Text & "','" & txthost.Text & "','" & cmbtype.Text & "','" & txtport.Text & "')"
SaveData(SQLStatement)
SQLConnection.Open()
SQLStatement = "INSERT INTO credentials(hosts_linked_id, username, password, type) VALUES('" & txtname.Text & "','" & txtusername.Text & "','" & encryptedpassword & "','" & cmbtype.Text & "')"
SaveData(SQLStatement)
Else
SQLConnection.Close()
End If
Also, here's the 'SaveData' function...
Public Sub SaveData(ByRef SQLStatement As String)
Dim cmd As MySqlCommand = New MySqlCommand
With cmd
.CommandText = SQLStatement
.CommandType = CommandType.Text
.Connection = SQLConnection
.ExecuteNonQuery()
End With
SQLConnection.Close()
MsgBox("Host has been added")
txtname.Text = ""
txtdescription.Text = ""
txthost.Text = ""
cmbtype.Text = ""
txtport.Text = ""
End Sub
What i need to do is get the id of the record created when my first 'INSERT' statement is executed into a variable so i can insert it into the 'credentials' table when my second 'INSERT' statement is executed.
I've googled the hell out of this and tried a few different methods, all without success.
Can anyone help point me in the right direction?
Thanks in advance!!
TL;DR: Need to get the ID of mysql record added when insert statement is executed and drop it into a variable