Related
Here I am trying to save information to two tables (using vb.net); students(parent table) and guardians(child). The relationship between the tables has already been created, Foreign Key(guardian id) which auto increments. Below is my code, your help will be appreciated.
Dim cn As New MySqlConnection
Dim cmd As New MySqlCommand
Dim dr As MySqlDataReader
cn.ConnectionString = "Server=localhost; user id='root'; password='' ; database='dbname'"
cmd.Connection = cn
cn.Open()
cmd.CommandText = "Select stud_id, firstname, lastname, dob, sickness, sex, pin, payment_type, level_stream FROM students WHERE stud_id = '" & txtstud_id.Text & "'"
'cmd.CommandText = "Select guardian_id, firstname1, lastname1, sex1, occupation, relationship, address, cell, telephone, email FROM guardians WHERE guardian_id = '" & txtgid.Text & "'"
dr = cmd.ExecuteReader
If dr.HasRows Then
MsgBox("Student ID already exist!", MsgBoxStyle.Critical, "Checkpoint")
Else
cmd.Dispose()
dr.Dispose()
cmd.CommandText = " Insert into students (stud_id, firstname, lastname, dob, sickness, sex, pin, payment_type, level_stream) Values ('" & txtstud_id.Text & "','" & txtfname.Text & "','" & txtlname.Text & "','" & DateTimePicker1.Text & "','" & txtsickness.Text & "','" & cmbsex.Text & "','" & txtpin.Text & "','" & cmbpay_opt.Text & "','" & cmblevel_stream.Text & "')"
'cmd1.CommandText = " Insert into guardians (guardian_id, firstname1, lastname1, sex1, occupation, relationship, address, cell, telephone, email) Values ('" & txtgid.Text & "','" & txtfname1.Text & "','" & txtlname1.Text & "','" & cmbsex1.Text & "','" & txtoccupation.Text & "', '" & txtrelationship.Text & "','" & txtaddress.Text & "', '" & txtcell.Text & "','" & txttel.Text & "','" & txtemail.Text & "')"
cmd.ExecuteNonQuery()
MsgBox("Information successfully saved", MsgBoxStyle.Information, "Saving data succeed")
txtstud_id.Clear()
txtstud_id.Focus()
txtfname.Clear()
txtlname.Clear()
DateTimePicker1.Text = String.Empty
cmbsex.Text = String.Empty
txtpin.Clear()
txtsickness.Clear()
txtgid.Clear()
txtfname1.Clear()
txtlname1.Clear()
cmbsex1.Text = String.Empty
txtoccupation.Clear()
txtrelationship.Clear()
cmbpay_opt.Text = String.Empty
txtaddress.Clear()
txtcell.Clear()
txttel.Clear()
txtemail.Clear()
cmblevel_stream.Text = String.Empty
End If
Here is an example for separate executions according to what I said in comments
Please read comments in the code segment.
Dim cn As New MySqlConnection
//''1st Commnad variable
Dim cmd As New MySqlCommand
//''2nd Commnad variable
Dim cmd1 As New MySqlCommand
//''3rd Commnad variable
Dim cmd2 As New MySqlCommand
Dim dr As MySqlDataReader
cn.ConnectionString = "Server=localhost; user id='root'; password='' ; database='dbname'"
cmd.Connection = cn
cn.Open()
cmd.CommandText = "Select stud_id, firstname, lastname, dob, sickness, sex, pin, payment_type, level_stream FROM students WHERE stud_id = '" & txtstud_id.Text & "'"
dr = cmd.ExecuteReader
If dr.HasRows Then
MsgBox("Student ID already exist!", MsgBoxStyle.Critical, "Checkpoint")
cmd.Dispose()
dr.Dispose()
cn.Close()
Else
cmd.Dispose()
dr.Dispose()
//'In this case you don't want to close the connection because you executing another queries too.
//'otherwise you have to check connection status and do open or close according to the status.
//'For Example
//'If (cn.State = ConnectionState.Closed)Then
//' cn.Open()
//'End if
cmd1.Connection = cn
cmd1.CommandText = " Insert into students (stud_id, firstname, lastname, dob, sickness, sex, pin, payment_type, level_stream) Values ('" & txtstud_id.Text & "','" & txtfname.Text & "','" & txtlname.Text & "','" & DateTimePicker1.Text & "','" & txtsickness.Text & "','" & cmbsex.Text & "','" & txtpin.Text & "','" & cmbpay_opt.Text & "','" & cmblevel_stream.Text & "')"
cmd1.ExecuteNonQuery()
cm1.Dispose()
cmd2.Connection = cn
cmd2.CommandText = " Insert into guardians (guardian_id, firstname1, lastname1, sex1, occupation, relationship, address, cell, telephone, email) Values ('" & txtgid.Text & "','" & txtfname1.Text & "','" & txtlname1.Text & "','" & cmbsex1.Text & "','" & txtoccupation.Text & "', '" & txtrelationship.Text & "','" & txtaddress.Text & "', '" & txtcell.Text & "','" & txttel.Text & "','" & txtemail.Text & "')"
cmd2.ExecuteNonQuery()
cmd2.Dispose()
//'Close when its over. otherwise you have to check whether connection is open or not before you start trans queries to database server. See else statement comments for example.
cn.Close()
MsgBox("Information successfully saved", MsgBoxStyle.Information, "Saving data succeed")
End If
//'Disposing cmd and dr
You can use same command but you have to think how to use it. Once you execute a command or datareader you have to Dispose it. And more concern about connection property to Closed or Open.
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"
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?
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 "..."
I am working on part of a application that needs to import data from a excel sheet into a mysql database table. The code works fine until it gets to a record in the excel sheet where one of the string values gets assigned "ABCDE All'John D Doe 999 West Lame Blvd Cullman, AL 35055". I am not certain but I believe that it has to do completely with the "'" that appears there. Which that can not change and other records from the excelsheet could contain the " ' " as well... When it gets to this record it throws this error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'John D Doe','ABCDE','All'John','D','Doe','256-555-5555',' ','256-555-5555' at line 1
the code that i have around this problems is as follows:
Private Function PerFormUpdate(ByVal customer As String, ByVal bill_to As String, ByVal Contact As String, ByVal Company As String, ByVal firstName As String, ByVal mi As String, ByVal lastname As String, ByVal phone As String, ByVal altPhone As String, ByVal fax As String)
Dim _db As New schoolEntities
Dim command As MySqlCommand = _dbconn.CreateCommand()
command.CommandText = "SELECT * FROM quickbooks_imports WHERE Customer= "" & _customer& "" & Bill_to= "" & _bill_to& "" & Contact= "" & _Company& ""& First_Name= "" & _firstName& "" & M_I= "" & _mi& "" & Last_Name= "" & _lastname& "" & Phone= "" & _phone& "" & Alt_Phone= "" & _altPhone& "" & Fax= "" & _Fax& """
_dbconn.Open()
Dim _mysqlReader As MySqlDataReader = command.ExecuteReader()
_dbconn.Close()
If Not _mysqlReader.HasRows Then
Dim _UpdateItem As New quickbooks_imports
Dim updateCommand As MySqlCommand = _dbconn.CreateCommand()
_UpdateItem.Customer = customer
_UpdateItem.Bill_to = bill_to
_UpdateItem.Contact = Contact
_UpdateItem.Company = Company
_UpdateItem.First_Name = firstName
_UpdateItem.M_I = mi
_UpdateItem.Last_Name = lastname
_UpdateItem.Phone = phone
_UpdateItem.Alt_Phone = altPhone
_UpdateItem.Fax = fax
updateCommand.CommandText = "INSERT INTO quickbooks_imports(Customer,Bill_to,Contact,Company,First_Name,M_I,Last_Name,Phone,Alt_Phone,Fax) VALUES ('" & _UpdateItem.Customer & "','" & _UpdateItem.Bill_to & "','" & _UpdateItem.Contact & "','" & _UpdateItem.Company & "','" & _UpdateItem.First_Name & "','" & _UpdateItem.M_I & "','" & _UpdateItem.Last_Name & "','" & _UpdateItem.Phone & "','" & _UpdateItem.Alt_Phone & "','" & _UpdateItem.Fax & "') "
_dbconn.Open()
updateCommand.ExecuteNonQuery()
_db.SaveChanges()
The Error shows up on the ExecuteNonQuery to perform the update..
Any help would be greatly appreciated...
As per your response I switched to the params and this is the new code:
updateCommand.CommandText = "INSERT INTO quickbooks_imports (Customer,Bill_to,Contact,Company,First_Name,M_I,Last_Name,Phone,Alt_Phone,Fax) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"
updateCommand.Parameters.AddWithValue("Customer", _UpdateItem.Customer)
updateCommand.Parameters.AddWithValue("Bill_to", _UpdateItem.Bill_to)
updateCommand.Parameters.AddWithValue("Contact", _UpdateItem.Contact)
updateCommand.Parameters.AddWithValue("Company", _UpdateItem.Company)
updateCommand.Parameters.AddWithValue("First_Name", _UpdateItem.First_Name)
updateCommand.Parameters.AddWithValue("M_I", _UpdateItem.M_I)
updateCommand.Parameters.AddWithValue("Last_Name", _UpdateItem.Last_Name)
updateCommand.Parameters.AddWithValue("Phone", _UpdateItem.Phone)
updateCommand.Parameters.AddWithValue("Alt_Phone", _UpdateItem.Alt_Phone)
updateCommand.Parameters.AddWithValue("Fax", _UpdateItem.Fax)
how ever its throwing a fatal exception now...
I just tried using name parameters as you mentioned in your reply and the code is as follows:
Private Function PerFormUpdate(ByVal customer As String, ByVal bill_to As String, ByVal Contact As String, ByVal Company As String, ByVal firstName As String, ByVal mi As String, ByVal lastname As String, ByVal phone As String, ByVal altPhone As String, ByVal fax As String)
Dim _db As New schoolEntities
Dim command As MySqlCommand = _dbconn.CreateCommand()
command.CommandText = "SELECT * FROM quickbooks_imports WHERE Customer= "" & _customer& "" & Bill_to= "" & _bill_to& "" & Contact= "" & _Company& ""& First_Name= "" & _firstName& "" & M_I= "" & _mi& "" & Last_Name= "" & _lastname& "" & Phone= "" & _phone& "" & Alt_Phone= "" & _altPhone& "" & Fax= "" & _Fax& """
_dbconn.Open()
Dim _mysqlReader As MySqlDataReader = command.ExecuteReader()
_dbconn.Close()
If Not _mysqlReader.HasRows Then
Dim _UpdateItem As New quickbooks_imports
Dim updateCommand As MySqlCommand = _dbconn.CreateCommand()
_UpdateItem.Customer = customer
_UpdateItem.Bill_to = bill_to
_UpdateItem.Contact = Contact
_UpdateItem.Company = Company
_UpdateItem.First_Name = firstName
_UpdateItem.M_I = mi
_UpdateItem.Last_Name = lastname
_UpdateItem.Phone = phone
_UpdateItem.Alt_Phone = altPhone
_UpdateItem.Fax = fax
updateCommand.CommandText = "INSERT INTO quickbooks_imports (Customer,Bill_to,Contact,Company,First_Name,M_I,Last_Name,Phone,Alt_Phone,Fax) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
updateCommand.Parameters.AddWithValue("#Customer", _UpdateItem.Customer)
updateCommand.Parameters.AddWithValue("#Bill_to", _UpdateItem.Bill_to)
updateCommand.Parameters.AddWithValue("#Contact", _UpdateItem.Contact)
updateCommand.Parameters.AddWithValue("#Company", _UpdateItem.Company)
updateCommand.Parameters.AddWithValue("#First_Name", _UpdateItem.First_Name)
updateCommand.Parameters.AddWithValue("#M_I", _UpdateItem.M_I)
updateCommand.Parameters.AddWithValue("#Last_Name", _UpdateItem.Last_Name)
updateCommand.Parameters.AddWithValue("#Phone", _UpdateItem.Phone)
updateCommand.Parameters.AddWithValue("#Alt_Phone", _UpdateItem.Alt_Phone)
updateCommand.Parameters.AddWithValue("#Fax", _UpdateItem.Fax)
'updateCommand.CommandText = "INSERT INTO EXCEL (id,Customer,Bill_to,Contact,Company,First_Name,M_I,Last_Name,Phone,Alt_Phone,Fax) VALUES ('" & _UpdateItem.id & "','" & _UpdateItem.Customer & "','" & _UpdateItem.Bill_to & "','" & _UpdateItem.Contact & "','" & _UpdateItem.Company & "','" & _UpdateItem.First_Name & "','" & _UpdateItem.M_I & "','" & _UpdateItem.Last_Name & "','" & _UpdateItem.Phone & "','" & _UpdateItem.Alt_Phone & "','" & _UpdateItem.Fax & "') ON DUPLICATE KEY UPDATE Customer= '" & _UpdateItem.Customer & "' Bill_to= '" & _UpdateItem.Bill_to & "' Contact= '" & _UpdateItem.Contact & "' Company= '" & _UpdateItem.Company & "' First_Name= '" & _UpdateItem.First_Name & "' M_I= '" & _UpdateItem.M_I & "' Last_Name= '" & _UpdateItem.Last_Name & "' Phone= '" & _UpdateItem.Phone & "' Alt_Phone= '" & _UpdateItem.Alt_Phone & "' Fax= '" & _UpdateItem.Fax & "'"
'updateCommand.CommandText = "INSERT INTO quickbooks_imports (Customer,Bill_to,Contact,Company,First_Name,M_I,Last_Name,Phone,Alt_Phone,Fax) VALUES ('" & _UpdateItem.Customer & "','" & _UpdateItem.Bill_to & "','" & _UpdateItem.Contact & "','" & _UpdateItem.Company & "','" & _UpdateItem.First_Name & "','" & _UpdateItem.M_I & "','" & _UpdateItem.Last_Name & "','" & _UpdateItem.Phone & "','" & _UpdateItem.Alt_Phone & "','" & _UpdateItem.Fax & "') "
_dbconn.Open()
updateCommand.ExecuteNonQuery()
_db.SaveChanges()
and I am still getting the fatal exception on the updateCommand.ExecuteNonQuery()
Fatal error encountered during command execution.
InnerException Message: "Parameter '?' must be defined."
You need to use parameters which will properly escape your strings for database execution.
Refer to this link. http://www.devart.com/dotconnect/mysql/docs/Parameters.html
Edit: Try using named parameters instead:
updateCommand.CommandText = "INSERT INTO quickbooks_imports (Customer,Bill_to,Contact,Company,First_Name,M_I,Last_Name,Phone,Alt_Phone,Fax) VALUES ("#Customer", "#Bill_to", "#Contact", "#Company", "#First_Name", "#M_I", "#Last_Name", "#Phone", "#Alt_Phone", "#Fax")"
updateCommand.Parameters.AddWithValue("#Customer", _UpdateItem.Customer)
updateCommand.Parameters.AddWithValue("#Bill_to", _UpdateItem.Bill_to)
updateCommand.Parameters.AddWithValue("#Contact", _UpdateItem.Contact)
updateCommand.Parameters.AddWithValue("#Company", _UpdateItem.Company)
updateCommand.Parameters.AddWithValue("#First_Name", _UpdateItem.First_Name)
updateCommand.Parameters.AddWithValue("#M_I", _UpdateItem.M_I)
updateCommand.Parameters.AddWithValue("#Last_Name", _UpdateItem.Last_Name)
updateCommand.Parameters.AddWithValue("#Phone", _UpdateItem.Phone)
updateCommand.Parameters.AddWithValue("#Alt_Phone", _UpdateItem.Alt_Phone)
updateCommand.Parameters.AddWithValue("#Fax", _UpdateItem.Fax)