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
Related
System.Data.SqlClient.SqlException: 'An explicit value for the identity column in table 'table1' can only be specified when a column list is used and IDENTITY_INSERT is ON.'
when i run the code it displays the error below
this is what pops up
**this is my code**
Imports System.Data.SqlClient
Public Class ARRIVAL
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
con.ConnectionString = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\PRINCE\Documents\real.mdf;Integrated Security=True;Connect Timeout=30"
If con.State = ConnectionState.Open Then
con.Close()
End If
con.Open()
disp_data()
End Sub
Private Sub insert_Click(sender As Object, e As EventArgs) Handles insert.Click
cmd = con.CreateCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText = "insert into table1 values('" & DateTimePicker1.Text & "','" & shiftsupervisorcb.SelectedItem.ToString() & "','" & teammemberscb.SelectedItem.ToString() & "','" & airlinecb.SelectedItem.ToString() & "','" & DateTimePicker2.Text & "','" & conternocb.SelectedItem.ToString() & "','" + TextBox2.Text + "','" + TextBox3.Text + "','" & linemanagercb.SelectedItem.ToString() & "','" & okimechcb.SelectedItem.ToString & "','" & okiribboncb.SelectedItem.ToString() & "','" + ocrcb.SelectedItem.ToString() & "','" & mousecb.SelectedItem.ToString() & "' ,'" & okiprinhcb.SelectedItem.ToString() & "','" & atbcb.SelectedItem.ToString() & "','" & btpcb.SelectedItem.ToString() & "','" & bgrcb.SelectedItem.ToString() & "')"
cmd.ExecuteNonQuery()
disp_data()
MessageBox.Show("record inserted successfully")
End Sub
Public Sub disp_data()
cmd = con.CreateCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText = "select * from table1"
cmd.ExecuteNonQuery()
Dim dt As New DataTable()
Dim da As New SqlDataAdapter(cmd)
da.Fill(dt)
DataGridView1.DataSource = dt
End Sub
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
Me.Hide()
Dim back = New BORDING
back.Show()
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
End Sub
Private Sub bgrcb_SelectedIndexChanged(sender As Object, e As EventArgs) Handles bgrcb.SelectedIndexChanged
End Sub
End Class
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
I somehow can't insert data into my MySQL database but I know there's no trouble with the query cause there is no error message and it can make it as far as the Success message box. I think the query is right for MySQL but it is not the specific one that I should use for INSERT INTO.
Here's my code:
Imports MySql.Data.MySqlClient
Public Class Register
Dim ServerString As String = "Server=localhost; UserId =root; Password = ; Database = gym;"
Dim MysqlConn As MySqlConnection = New MySqlConnection
Dim COMMAND As MySqlCommand
Dim password, pass As String
Dim member As Integer
Private Sub Register_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.CenterToParent()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
MysqlConn.ConnectionString = ServerString
Dim READER As MySqlDataReader
password = TextBox2.Text
pass = TextBox3.Text
confirm(password, pass)
If TextBox1.Text = Nothing Or TextBox2.Text = Nothing Or TextBox3.Text = Nothing Or TextBox4.Text = Nothing Or TextBox5.Text = Nothing Or TextBox6.Text = Nothing Or DateTimePicker1.Text = Nothing Or RadioButton1.Checked = False And RadioButton2.Checked = False Then
MsgBox("Please Fill your Information Completely")
Else
MysqlConn.ConnectionString = ServerString
Try
MysqlConn.Open()
Dim query As String
query = "select * from gym.user where user_name ='" & TextBox1.Text & "'"
COMMAND = New MySqlCommand(query, MysqlConn)
READER = COMMAND.ExecuteReader
Dim count As Integer
While READER.Read
count = count + 1
End While
MysqlConn.Close()
If count > 0 Then
MsgBox("User Already Exists")
Else
MysqlConn.Open()
query = "INSERT INTO gym.user(user_name,user_password,user_firstname,user_lastname,user_birthday,user_contact,user_membership) VALUES ('" & TextBox1.Text & "', md5('" & TextBox2.Text & "') ,'" & TextBox4.Text & "','" & TextBox5.Text & "','" & DateTimePicker1.Value.Date & "','" & TextBox6.Text & "','" & member & "')"
COMMAND = New MySqlCommand(query, MysqlConn)
MsgBox("USER REGISTERED")
MysqlConn.Close()
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
MysqlConn.Dispose()
End Try
End If
End Sub
You're missing ExecuteNonQuery statement:
query = "INSERT INTO gym.user(user_name,user_password,user_firstname,user_lastname,user_birthday,user_contact,user_membership) VALUES ('" & TextBox1.Text & "', md5('" & TextBox2.Text & "') ,'" & TextBox4.Text & "','" & TextBox5.Text & "','" & DateTimePicker1.Value.Date & "','" & TextBox6.Text & "','" & member & "')"
COMMAND = New MySqlCommand(query, MysqlConn)
COMMAND.ExecuteNonQuery()
Here's the code of my button_click:
Private Sub Button10_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button10.Click
Dim conn As New MySqlConnection
Dim cmd As New MySqlCommand
Dim dr As MySqlDataReader
conn.ConnectionString = "server = localhost; user id = root; database = db; password = root"
cmd.Connection = conn
conn.Open()
cmd.CommandText = " SELECT * FROM candidate WHERE idn = '" & TextBox4.Text & "'"
dr = cmd.ExecuteReader
If dr.HasRows Then
MessageBox.Show("Entry I.D. No. already exist", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
ElseIf TextBox4.Text = "" Or TextBox5.Text = "" Or TextBox6.Text = "" Or TextBox7.Text = "" Or ComboBox1.Text = "" Or TextBox3.Text = "" Then
MessageBox.Show("Please complete the required fields..", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Else
conn.Close()
con.ConnectionString = "server = localhost; user id = root; database = db; password = root"
cmd.Connection = con
con.Open()
Dim sqlQuery As String = "INSERT INTO candidate(idn,cfname,cmname,clname,cyr,sec,vyear,votes,pword) VALUES('" & TextBox4.Text & "','" & TextBox5.Text & "','" & TextBox6.Text & "','" & TextBox7.Text & "','" & ComboBox1.Text & "','" & TextBox3.Text & "',CONCAT(YEAR(NOW()),'-',(YEAR(NOW()) + 1),'0','" & TextBox2.Text & "')"
Dim sqlCommand As New MySqlCommand
With sqlCommand
.CommandText = sqlQuery
.Connection = con
.ExecuteNonQuery()
End With
MsgBox("Record Inserted")
End If
End Sub
what's wrong with my INSERT query? I can't seem to find anything wrong here, but VB.NET says it has error in " at line 1?
"INSERT INTO candidate(vyear) VALUES(CONCAT(YEAR(NOW()),'-',(YEAR(NOW()) + 1))"
There is a unbalanced open parenthesis before the second YEAR. Need to remove it
"INSERT INTO candidate(vyear) VALUES( CONCAT(YEAR(NOW()),'-',YEAR(NOW()) + 1) )"
Looking at the updated code you really need to start to use parameterized queries
Using con = new MySqlConnection(......)
Using cmd = con.CreateCommand()
con.Open()
Dim sqlQuery As String = "INSERT INTO candidate " & _
"(idn,cfname,cmname,clname,cyr,sec,vyear,votes,pword) VALUES(" & _
"#idn, #cfname, #cmname, #clname, #cyr, #sec, " & _
"CONCAT(YEAR(NOW()),'-',YEAR(NOW()) + 1), " & _
"#votes, #pword"
With cmd
.CommandText = sqlQuery
' is idn an integer field, then pass it as integer.
' instead if it is an autoincrement then remove it and let the db calculate for you
.Parameters.AddWithValue("#idn", Convert.ToInt32(TextBox4.Text))
.Parameters.AddWithValue("#cfname, TextBox5.Text)
.... and so on for every placeholder in the parameterized text above
.ExecuteNonQuery()
End With
MsgBox("Record Inserted")
End Using
End Using
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.