save listview data in mysql query browser database - mysql

Dim lvitem As Object
Dim iCount As Integer
Dim iLoop As Integer
Dim query3 = New SqlCommand
query3.Connection = New SqlConnection("SERVER=localhost;UID=root;DATABASE=test;")
iCount = lvLogs.Items.Count()
If Not lvLogs.Items.Count = 0 Then
Do Until iLoop = lvLogs.Items.Count
lvitem = lvLogs.Items.Item(iLoop)
With LvItem
query3.CommandText = "insert into wer(CustomerName,SalesGroup,CustomerType,TypeOfIndustry,RM,SeniorRM) values('" & .SubItems(0).Text & "','" & .SubItems(1).Text & "','" & .SubItems(2).Text & "','" & .SubItems(3).Text & "','" & .SubItems(4).Text & "','" & .SubItems(5).Text & "')"
query3.ExecuteNonQuery()
End With
iLoop = iLoop + 1
LvItem = Nothing
Loop
End If
MessageBox.Show("Record Saved!")
That is my code. message box show up but the record is not saved in my database. please help me

You can't use SqlClient provider. You must have to use MySql .net connector API and take a look at MySql connector examples.

Related

Return the Auto Incremented ID number of the current inserted row in VB.Net from mysql database

I am using VB.net to write a recipe to a mysql database.
Once i have inserted the recipe, I need to return the Auto Incremented id number for that row. (Auto Incremented id Column name is RecipeID)
I have tried different variations of this question:
Return Last ID (IDENTITY) On Insert row VB.NET MySQL
but keep getting unhandled exception errors.
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Dim mytimestamp As String = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
MysqlConn = New MySqlConnection
MysqlConn.ConnectionString = "server=localhost;userid=root;password=Splash123;database=awsbdata"
Dim reader As MySqlDataReader
Dim jobnumber As String = EthernetIPforCLXCom1.Read("BC_BatchCode")
Dim recipename As String = EthernetIPforCLXCom1.Read("Recipe_library[0].Name")
Dim recipeid As String = EthernetIPforCLXCom1.Read("Recipe_library[0].Number")
Dim perator As String = EthernetIPforCLXCom1.Read("BC_CurrentUser")
Dim slurrypress As Decimal = EthernetIPforCLXCom1.Read("PT1343_Imp")
Dim g1airpressure As Decimal = EthernetIPforCLXCom1.Read("PIT1022_Imp")
Dim g2airpressure As Decimal = EthernetIPforCLXCom1.Read("PIT1023_Imp")
Dim g3airpressure As Decimal = EthernetIPforCLXCom1.Read("PIT1024_Imp")
Dim g4airpressure As Decimal = EthernetIPforCLXCom1.Read("PIT1025_Imp")
Dim airflowcfm As Decimal = EthernetIPforCLXCom1.Read("FIT1042_Imp")
Dim concentration As Decimal = EthernetIPforCLXCom1.Read("MC_AbrasiveConcentation")
Dim tanklevel As Decimal = EthernetIPforCLXCom1.Read("LT1345_Imp")
Try
MysqlConn.Open()
Dim query As String
query = "insert into awsbdata.batchdata (RunTime,JobNumber,RecipeID,RecipeName,Operator,Concentration,G1AirPressure,G2AirPressure,G3AirPressure,G4AirPressure,AirFlow_CFM,SlurryPressure,TankLevel) values ('" & mytimestamp & "','" & jobnumber & "','" & recipeid & "','" & recipename & "','" & perator & "','" & concentration & "','" & g1airpressure & "','" & g2airpressure & "','" & g3airpressure & "','" & g4airpressure & "','" & airflowcfm & "','" & slurrypress & "','" & tanklevel & "')"
COMMAND = New MySqlCommand(query, MysqlConn)
reader = COMMAND.ExecuteReader
MysqlConn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
End Try
End Sub
I either get an unhandled exception or connection not open error
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Dim mytimestamp As String = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
MysqlConn = New MySqlConnection
MysqlConn.ConnectionString = "server=localhost;userid=root;password=Splash123;database=awsbdata"
Dim reader As MySqlDataReader
Dim jobnumber As String = EthernetIPforCLXCom1.Read("BC_BatchCode")
Dim recipename As String = EthernetIPforCLXCom1.Read("Recipe_library[0].Name")
Dim recipeid As String = EthernetIPforCLXCom1.Read("Recipe_library[0].Number")
Dim perator As String = EthernetIPforCLXCom1.Read("BC_CurrentUser")
Dim slurrypress As Decimal = EthernetIPforCLXCom1.Read("PT1343_Imp")
Dim g1airpressure As Decimal = EthernetIPforCLXCom1.Read("PIT1022_Imp")
Dim g2airpressure As Decimal = EthernetIPforCLXCom1.Read("PIT1023_Imp")
Dim g3airpressure As Decimal = EthernetIPforCLXCom1.Read("PIT1024_Imp")
Dim g4airpressure As Decimal = EthernetIPforCLXCom1.Read("PIT1025_Imp")
Dim airflowcfm As Decimal = EthernetIPforCLXCom1.Read("FIT1042_Imp")
Dim concentration As Decimal = EthernetIPforCLXCom1.Read("MC_AbrasiveConcentation")
Dim tanklevel As Decimal = EthernetIPforCLXCom1.Read("LT1345_Imp")
Try
MysqlConn.Open()
Dim query As String
query = "insert into awsbdata.batchdata (RunTime,JobNumber,RecipeID,RecipeName,Operator,Concentration,G1AirPressure,G2AirPressure,G3AirPressure,G4AirPressure,AirFlow_CFM,SlurryPressure,TankLevel) values ('" & mytimestamp & "','" & jobnumber & "','" & recipeid & "','" & recipename & "','" & perator & "','" & concentration & "','" & g1airpressure & "','" & g2airpressure & "','" & g3airpressure & "','" & g4airpressure & "','" & airflowcfm & "','" & slurrypress & "','" & tanklevel & "')"
COMMAND = New MySqlCommand(query, MysqlConn)
reader = COMMAND.ExecuteReader
MysqlConn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
End Try
Try
MysqlConn.Open()
COMMAND.CommandText = "SELECT Last_insert_id()"
Dim lastID = COMMAND.ExecuteScalar()
MsgBox(lastID)
MysqlConn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
End Try
End Sub

Adding listview items to sqlyog

I'm making a Sales and inventory system at my school. I'd like to save the listview items to my database which is a MySQL sqlyog ultimate.
This is my connection and my code for saving listview to database but I get the error Object variable or with block variable is not set.
Imports MySql.Data.MySqlClient
Module modconnector
Public sqlcmd As New MySqlCommand
Public sqlcon As New MySqlConnection
Public sqladapter As New MySqlDataAdapter
Public sqlreader As MySqlDataReader
Public strsql As String
Sub connect()
sqlcon.ConnectionString = ("server=localhost;user id=root;password= ;database=sais")
sqlcon.Open()
End Sub
Sub savelistview()
sqlcon.Close()
connect()
iCount = ListView1.Items.Count()
If Not ListView1.Items.Count = 0 Then
Do Until iLoop = ListView1.Items.Count
With lvitem
lvitem = ListView1.Items.Item(iLoop)
strsql = "insert into transaction(prod_code,prod_description,prod_price,order,quantity,date) values('" _
& .Items(0).Text & "','" _
& .SubItems(1).Text & "','" _
& .SubItems(2).Text & "','" _
& .SubItems(3).Text & "','" _
& .SubItems(4).Text & "','" _
& .SubItems(5).Text & "','" _
& Label26.Text & "')"
sqlcmd.CommandText = strsql
sqlcmd.Connection = sqlcon
sqladapter.SelectCommand = sqlcmd
sqlcmd.ExecuteNonQuery()
End With
lvitem = Nothing
iLoop = iLoop + 1
Loop
End If
MessageBox.Show("Record Saved!")
sqlcon.Close()
End Sub
End Module

operator use for a combo box in vb.net

this years is a sample of combo box. what should i do for this to have not error?`
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles save.Click
Dim genderval As String
Dim birthdate As String
birthdate = bday.Value.ToString()
If babae.Checked = True Then
genderval = "Female"
Else
genderval = "Male"
End If
query = "insert into studentinfo(Lastname,Firstname,middlename,birthdate,gender,age,studentyear,username,accountpassword,confirmpassword) values('" & familynem.Text & "','" & givennem.Text & "','" & middlenem.Text & "','" & birthdate & "','" & genderval & "','" & Edaad.Text & "','" *years* "','" & usename.Text & "','" & accpass.Text & "','" & confirmpass.Text & "')"
con.Open()
cmd = New SqlCommand(query, con)
cmd.ExecuteNonQuery()
con.Close()
dataReload()
user.Show()
Me.Hide()
End Sub
End Class
You need to access ComboBox by it's properties and not Directly
Use Years.Text or Years.SelectedValue instead of Years
Try this
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles save.Click
Dim genderval As String
Dim birthdate As String
birthdate = bday.Value.ToString()
If babae.Checked = True Then
genderval = "Female"
Else
genderval = "Male"
End If
query = "insert into studentinfo(Lastname,Firstname,middlename,birthdate,gender,age,studentyear,username,accountpassword,confirmpassword) values('" & familynem.Text & "','" & givennem.Text & "','" & middlenem.Text & "','" & birthdate & "','" & genderval & "','" & Edaad.Text & "','" Years.Text "','" & usename.Text & "','" & accpass.Text & "','" & confirmpass.Text & "')"
con.Open()
cmd = New SqlCommand(query, con)
cmd.ExecuteNonQuery()
con.Close()
dataReload()
user.Show()
Me.Hide()
End Sub
End Class
This kind of errors are common when you use a concatenation string. Somewhere one or more of your strings value contains an invalid character that breaks the syntax of the sql command.
For example, if one of your textboxes contains a single quote, the resulting query text would be invalid. Also, it is not clear what is years. If it is a combobox then you need to extract its value through the property Text (or SelectedValue, or SelectedItem). Another thing to be aware of is the matching between the parameters value and the underlying column datatype. They should be the same, so for integers fields you need to add a conversion from the textbox text (Age?)
The answer as usual are parameterized queries that remove this kind of errors and the Sql Injection vulnerability
query = "insert into studentinfo " & _
"(Lastname,Firstname,middlename,birthdate,gender,age," & _
"studentyear,username,accountpassword,confirmpassword) " & _
"values(#family,#given,#mname,#dob,#gender,#eda,#years,#uname,#pwd,#cpwd)"
con.Open()
// cmd = New SqlCommand(query, con)
cmd = new MySqlCommand(query, con)
cmd.Parameters.AddWithValue("#family",familynem.Text)
cmd.Parameters.AddWithValue("#given",givennem.Text)
cmd.Parameters.AddWithValue("#mname",middlenem.Text )
cmd.Parameters.AddWithValue("#dob",birthdate)
cmd.Parameters.AddWithValue("#gender",genderval )
cmd.Parameters.AddWithValue("#eda",Edaad.Text) ' or Convert.ToInt32(Edaad.Text)
cmd.Parameters.AddWithValue("#years",years.Text)
cmd.Parameters.AddWithValue("#uname",usename.Text )
cmd.Parameters.AddWithValue("#pwd",accpass.Text )
cmd.Parameters.AddWithValue("#cpwd",confirmpass.Text )
cmd.ExecuteNonQuery()
By the way, you have tagged this question with MySql but you are using a SqlCommand. What is the right database to use?

Duplicate record in mysql after INSERT

Quick one for you.
I'm using the following code to insert a record into two tables in my mysql db...
SQLConnection.ConnectionString = connectionstring
Try
If SQLConnection.State = ConnectionState.Closed Then
SQLConnection.Open()
Dim SQLStatement As String = "INSERT INTO hosts(name, description, host, type, port, hostname) VALUES('" & txtname.Text & "','" & txtdescription.Text & "','" & txthost.Text & "','" & cmbtype.Text & "','" & txtport.Text & "','" & Pinger.resolvedstatus.Text & "'); SELECT LAST_INSERT_ID()"
SaveData(SQLStatement)
SQLConnection.Open()
SQLStatement = "INSERT INTO credentials(hosts_linked_id, username, password, type) VALUES('" & hosts_linked_id & "','" & txtusername.Text & "','" & txtpwd.Text & "','" & cmbtype.Text & "')"
SaveData(SQLStatement)
the Savedata() bit calls this function...
Public Sub SaveData(ByRef SQLStatement As String)
Dim cmd As MySqlCommand = New MySqlCommand
cmd.CommandText = SQLStatement
cmd.CommandType = CommandType.Text
cmd.Connection = SQLConnection
cmd.ExecuteNonQuery()
hosts_linked_id = CInt(cmd.ExecuteScalar())
SQLConnection.Close()
MsgBox("Host has been added - Host ID " & hosts_linked_id & "")
txtname.Text = ""
txtdescription.Text = ""
txthost.Text = ""
cmbtype.Text = ""
txtport.Text = ""
End Sub
The code is working in that the necessary records are inserted into both the 'hosts' and 'credentials' tables, however in each table the record is inserted twice.
obviously I don't want duplicate records in my db, so can anyone help me stop it from performing the insert twice?
Thanks in advance!!
You call it twice:
cmd.ExecuteNonQuery()
hosts_linked_id = CInt(cmd.ExecuteScalar())
Once as ExecuteNonQuery and second time as ExecuteScalar()
You need to remove one of them. Looking at the code, I guess maybe you need to introduce a parameter to SaveData method to say which one to use.
cmd.ExecuteNonQuery()
hosts_linked_id = CInt(cmd.ExecuteScalar())
Remove cmd.ExecuteNonQuery() To avoid Insert Twice

Adding data from Excel to Mysql via VBA

UPDATED QUESTION...SEE BELOW
I have an excel sheet which accesses a MySQL db as a backend....
I insert new records into MySql the following way, but I am not sure if this is the best way.
For rowline = 1 To 50
strSQL = myquerystring (INSERT 5 columns per excel row)
rs.Open strSQL, oConn, adOpenDynamic, adLockOptimistic
Next rowline
Basically the query string goes through each row in excel sheet (from 1 to 50) and the data on certain cells are added to the sql query and then inserted with rs.Open ....
(each row has some 5 columns which are inserted as a record)
Everything runs well, however I just want to know if there is a faster way (just one INSERT query), inserting all 50 (and 5 columns on each), from row 1 to 50, all at once.
At the moment it is doing 50 individual INSERT queries, so I am trying to reduce that to 1 but I don't know if it is possible.
NEW INFORMATION:
Hi, following your advice and links (thanks!) and some Googling, I ended up with the following code...
It works fine, HOWEVER to INSERT 100 rows it takes approx 15 seconds....this is far too much.
I am hoping I can get some code/ideas on how to Execute the query once, (inserting all 100 rows in one hit).
Please note that I am a beginner on this so if you can stir me into some samples on how it should be done it will be much appreciated.
Public Sub INSERT_to_MySQL()
Dim conn As ADODB.Connection
Dim cmd As ADODB.Command
Dim strSQL As String
app_enable_false
On Error GoTo no_DB_connection_error
resume_after_connecting:
Set cmd = New ADODB.Command
cmd.ActiveConnection = oConn
' LOOP and INSERT the data
' 100 rows take approx 15 seconds to INSERT
For rowcursor= 1 To 100
the_table = "`global`.`filesaved` "
strSQL = "INSERT INTO " & the_table & " (Client_Name, OriginCity, DestinationCity, ValidFrom, ValidTo, Quote_Number, Cost1, Cost2, Cost3) "
strSQL = strSQL & " VALUES ('" & esc(Range("BB" & rowcursor)) & "','" & esc(Range("BC" & rowcursor)) & "','" & esc(Range("BD" & rowcursor)) & "','" & Format(Range("BE" & rowcursor), "yyyy-mm-dd") & "','" & Format(Range("BF" & rowcursor), "yyyy-mm-dd")
strSQL = strSQL & "','" & esc(Range("BH" & rowcursor)) & "','" & esc(Range("BJ" & rowcursor)) & "','" & esc(Range("BK" & rowcursor)) & "','" & esc(Range("BJ" & rowcursor)) & "')"
cmd.CommandText = strSQL
cmd.Execute
Next rowcursor
app_enable_true
Exit Sub
no_DB_connection_error:
ConnectDB
GoTo resume_after_connecting
End Sub
I would move the open command outside the loop, then use the Execute method to do the inserts in the loop. You don't want to do an open on the database every time.
Here's a good page of ADO methods.
Here's a question on Batch Inserting (and Updating).
EDIT: Looking at Remou's link in his comment, I realized that you probably don't even need the open. Just use the Execute method for the Inserts.
Find below a process which works, in case someone else has in future same problem.
Might not be the best solution but 100 records are saved all at once in less than a second, which is what I was after. Also there is only one INSERT query done (instead of 100 different ones for each row.
Thanks to all for your guidance.
Dim conn As ADODB.Connection
Dim cmd As ADODB.Command
Dim rst_recordset As ADODB.Recordset
Dim strSQL As String
Dim strSQL2 as string
On Error GoTo no_DB_connection_error
resume_after_connecting:
Set cmd = New ADODB.Command
cmd.ActiveConnection = oConn
' LOOP and INSERT the data
lastrow = Range("BB65536").End(xlUp).Row
the_table = "`global`.`filesaved` "
strSQL = "INSERT INTO `global`.`filesaved` " & " (Client_Name, OriginCity, DestCity, ValidFrom, ValidTo, Quote_Number, Cost1, Cost2, Cost3) VALUES "
strSQL2 = ""
For excel_row = 1 To lastrow
strSQL2 = strSQL2 & " ('" & cells(excel_row,1) & "','" & cells(excel_row,2) & "','" & cells(excel_row,3) & "','" & cells(excel_row,4) & "','" & cells(excel_row,5) & "','" & cells(excel_row,6) & "','" & cells(excel_row,7) & "','" & cells(excel_row,8) & "','" & cells(excel_row,9) & "') ,"
next excel_row
strSQL = strSQL & strSQL2
Mid(strSQL, Len(strSQL), 1) = ";" ' gets rid of the last comma
cmd.CommandText = strSQL
cmd.Execute
If I run a statement and do not expect a reply back, I usually go for the Command object in VBA.
This code worked for me
Sub insertdata()
Dim year As String
Set rs = CreateObject("ADODB.Recordset")
Database_Name = Range("b3").Value ' Name of database
User_ID = Range("b4").Value 'id user or username
Password = Range("b5").Value 'Password
Server_Name =Range("b2").Value
' Query for fetching Maximum Date
' LOOP and INSERT the data
lastrow = Range("BB65536").End(xlUp).Row
the_table = "`admin`.`test` "
strSQL = "INSERT INTO `drawing`.`test` " & " (tests,test2) VALUES "
strSQL2 = ""
For excel_row = 1 To 100
strSQL2 = strSQL2 & " ('" & Cells(excel_row, 1) & "','" & Cells(excel_row, 2) & "') ,"
Next excel_row
strSQL = strSQL & strSQL2
Mid(strSQL, Len(strSQL), 1) = ";" '
' ADODB connection
Set Cn = CreateObject("ADODB.Connection") 'NEW STATEMENT
Cn.Open "Driver={MySQL ODBC 5.1 Driver};Server=" & Server_Name & ";Database=" & Database_Name & _
";Uid=" & User_ID & ";Pwd=" & Password & ";"
rs.Open strSQL, Cn, adOpenStatic
Dim myArray()
End Sub