operator use for a combo box in vb.net - mysql

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?

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

Combobox ValueMember not working with MySQL

My ComboBox controls display publishername and authorlastname and stores the publisherid and authorid.
When I run my code, it does display publishername and authorlastname with the ValueMember of publisherid and authorid however when the insert query runs it literally tries to insert the words _publisherid_ and _authorid_.
ComboBox Code:
Private Sub addbook_Load(sender As Object, e As EventArgs) Handles MyBase.Load
mysqlconn = New MySqlConnection
mysqlconn.ConnectionString = "server=localhost;userid=root;database=librarydatabase;Convert Zero Datetime=True"
Dim table As New DataTable
Dim da As New MySqlDataAdapter("select * from publishertable", mysqlconn)
da.Fill(table)
ComboBox1.DataSource = New BindingSource(table, Nothing)
ComboBox1.DisplayMember = "publishername"
ComboBox1.ValueMember = "PublisherId"
Dim pa As New MySqlDataAdapter("select * from authortable", mysqlconn)
pa.Fill(table)
ComboBox2.DataSource = New BindingSource(table, Nothing)
ComboBox2.DisplayMember = "authorlastname"
ComboBox2.ValueMember = "authorid"
End Sub
Insert Code:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button1.Click
conn = New MySqlConnection
conn.ConnectionString =
"server=localhost;userid=root;database=librarydatabase"
Dim reader As MySqlDataReader
Try
conn.Open()
query = "SET foreign_key_checks = 0;insert into booktable(ISBNno,bookname,dateofpublication,genre,duodecimal,copies,copiesinstock,authorid,publisherid) Values('" & ISBNno.Text & "','" & Title.Text & "','" & dateofpublication.Text & "','" & genre.Text & "','" & duodecimal.Text & "','" & copies.Text & "','" & copies.Text & "','" & ComboBox2.ValueMember & "', '" & ComboBox1.ValueMember & "');SET foreign_key_checks = 1"
command = New MySqlCommand(query, conn)
reader = command.ExecuteReader
MessageBox.Show(query)
conn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
conn.Dispose()
End Try
End Sub
You should be using SelectedValue instead of ValueMember
query = "SET foreign_key_checks = 0;insert into booktable(ISBNno,bookname,dateofpublication,genre,duodecimal,copies,copiesinstock,authorid,publisherid) Values('" & ISBNno.Text & "','" & Title.Text & "','" & dateofpublication.Text & "','" & genre.Text & "','" & duodecimal.Text & "','" & copies.Text & "','" & copies.Text & "','" & ComboBox2.ValueMember & "', '" & ComboBox1.ValueMember & "');SET foreign_key_checks = 1"
should be
query = "SET foreign_key_checks = 0;insert into booktable(ISBNno,bookname,dateofpublication,genre,duodecimal,copies,copiesinstock,authorid,publisherid) Values('" & ISBNno.Text & "','" & Title.Text & "','" & dateofpublication.Text & "','" & genre.Text & "','" & duodecimal.Text & "','" & copies.Text & "','" & copies.Text & "','" & ComboBox2.SelectedValue & "', '" & ComboBox1.SelectedValue & "');SET foreign_key_checks = 1"

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

Argument is not optional?

Private Sub cmdAdd_Click()
'add data to table
CurrentDb.Execute = "INSERT INTO jscbb_dir2(ID,Lastname,FirstName, PrimA, Artea,LubNum,OfficeNum,OfficePhone,Email,LabPhone,stats)" & _
" VALUES(" & Me.Textid & ",'" & Me.TextLast & "','" & Me.TextFirst & "','" & Me.Textprima & "','" & Me.Textarea & "','" & Me.Textlabnum & _
"','" & Me.Textofficenum & "','" & Me.Textofficephone & "','" & Me.Textemail & "','" & Me.Textlabphone & "','" & Me.Textstatus & "')"
'refresh data is list on focus
jscbb_dirsub.Form.Requery
End Sub
Why am I getting an error on the last (Me.Textstatus)? I know this is a low-level question, but I need another pair of eyes, I've been looking at this for over an hour. The error is "Compile Error: Argument Not Optional"
Consider parameters, they will be easier to debug.
Dim qdf As QueryDef
ssql = "INSERT INTO jscbb_dir2(ID,Lastname,FirstName,PrimA,Artea," _
& "LubNum,OfficeNum,OfficePhone,Email,LabPhone,stats) " _
& "VALUES([id],[last],[first],[prima],[area],[lab]," _
& "[office],[phone],[email],[stat])"
Set qdf = CurrentDb.CreateQueryDef("", ssql)
qdf.Parameters("id") = Me.TextID
qdf.Parameters("last") = Me.Textlast
qdf.Parameters("first") = Me.Textfirst
qdf.Parameters("prima") = Me.Textprima
qdf.Parameters("area") = Me.Textarea
qdf.Parameters("lab") = Me.Textlabnum
qdf.Parameters("office") = Me.Textofficenumbet
qdf.Parameters("phone") = Me.Textofficephone
qdf.Parameters("email") = Me.Textemail
qdf.Parameters("stat") = Me.Textstatus
qdf.Execute dbFailOnError
Execute is a method, not a property. You don't use = between a method and its arguments, so
CurrentDb.Execute = "..."
should be
CurrentDb.Execute "..."

save listview data in mysql query browser database

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.