INSERT INTO in MySQL not working but no errors? - mysql

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

Related

please what's the cause of this error in visual basic

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

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

I want to insert and retrieve data under one button event in vb.net with sql database

Here i am trying to register student's detail. and at the same time i want to retrieve a unique user id from connected SQL server and that's where i got stuck!
I want to know what i am doing wrong here!
Everything stored in the SQL server is correct and i have make an auto increment code in SQL!
so why its not inserting and retrieving the data simultaneously
Imports MySql.Data.MySqlClient
Public Class Form3
Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim con As New MySqlConnection("server=localhost;user id=root;password=root;persistsecurityinfo=True;database=bcaproject")
Dim cmd As New MySqlCommand
If TextBox1.Text = "" Or TextBox2.Text = "" Or TextBox3.Text = "" Or TextBox3.Text = "" Or TextBox4.Text = "" Or TextBox5.Text = "" Or TextBox6.Text = "" Then
MessageBox.Show("Information shouldn't be empty...")
Else
con.Open()
cmd.Connection = con
cmd.CommandText = "insert into student(F_name,L_name,Email,Phoneno,Username,Password) values('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "','" & TextBox5.Text & "','" & TextBox6.Text & "')"
cmd.ExecuteNonQuery()
MessageBox.Show("successfully Registered")
TextBox1.Text = ""
TextBox2.Text = ""
TextBox3.Text = ""
TextBox4.Text = ""
TextBox5.Text = ""
TextBox6.Text = ""
Form2.Show()
Me.Hide()
End If
End Sub
Private Sub Button2_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Form2.Show()
Me.Hide()
End Sub
Private Sub TextBox4_KeyPress1(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox4.KeyPress
If Asc(e.KeyChar) <> 8 Then
If Not IsNumeric(e.KeyChar) Then
tipvalidation.Show("Numeric input required", sender, 5000)
e.KeyChar = Nothing
End If
End If
End Sub
End Class

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

MySQL Syntax Error in VB.NET

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