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"
Related
written query execute successfully without any error but data is not getting saved.
Table_StockList is a Table not sure where i am making mistake . kindly assist.
Dim sid As String
Dim pnumber As String
Dim pname As String
Dim pmake As String
Dim pmodel As String
Dim phsn As String
Dim pdop As Date
Dim ppp As Currency
Dim pstatus As String
Dim psp As Currency
Dim paqty As Integer
Dim totalqty As Integer
Dim pinvoice As Attachment
sid = Me.Stock_ID.Value
pnumber = Me.Part_No.Value
pname = Me.Product_Name.Value
pmake = Me.Make.Value
pmodel = Me.Model.Value
phsn = Me.HSN.Value
pdop = Me.curpurchasedate.Value
ppp = Me.Purchase_Price_dr_.Value
pstatus = Me.Status.Value
psp = Me.Selling_price_cr_.Value
paqty = Me.availqty.Value
totalqty = Me.totalqty.Value
pinvoice = Me.Invoice
'Me.Recordset.MoveLast
DoCmd.RunCommand acCmdRecordsGoToLast
DoCmd.RunSQL "INSERT INTO Table_StockList ([Stock ID],[Part No],[Product Name],Make,Model,HSN,[Date of Purchase],Status,[Selling price(cr)],[Available QTY],[Total QTY])" & _
"VALUES('" & sid & "','" & pnumber & "','" & pname & "','" & pmake & "','" & pmodel & "','" & phsn & "','" & pdop & "','" & ppp & "','" & pstatus & "','" & psp & "','" & paqty & "','" & totalqty & "','" & pinvoice & "' )"
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.
Private Sub btnSave_ClientOrderStatus_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave_ClientOrderStatus.Click
mysqlconn = New MySqlConnection
mysqlconn.ConnectionString = serverstring
Try
mysqlconn.Open()
Dim query As String = "insert into isad.invoice_table(Invoice, Clientnumber, Firstname, Lastname, ProductID, Name, Price, Qty, Description, Total, DateCreated) values "
command = New MySqlCommand(query, mysqlconn)
For i = 0 To ListView1.Items.Count - 1
query &= "('" & txtInvoice_ClientOrderStatus.Text & "','" & txtClientNumber_ClientOrderStatus.Text.Replace("'", "\'") & "','" & txtFname_ClientOrderStatus.Text.Replace("'", "\'") & _
"', '" & txtLname_ClientOrderStatus.Text.Replace("'", "\'") & "', #ProductID" & i.ToString & ", #Name" & i.ToString & ", #Price" & i.ToString & _
", #Quantity" & i.ToString & ", #Description" & i.ToString & ", '" & txtTotal_ClientOrderStatus.Text & "',now())"
command.Parameters.AddWithValue("#ProductID" & i.ToString, ListView1.Items(i).Text)
command.Parameters.AddWithValue("#Name" & i.ToString, ListView1.Items(i).SubItems(1).Text)
command.Parameters.AddWithValue("#Price" & i.ToString, ListView1.Items(i).SubItems(2).Text)
command.Parameters.AddWithValue("#Quantity" & i.ToString, ListView1.Items(i).SubItems(3).Text)
command.Parameters.AddWithValue("#Description" & i.ToString, ListView1.Items(i).SubItems(4).Text)
query &= ", "
Next
query = query.Substring(0, query.Length - 2)
READER = command.ExecuteReader
SBP2.Text = "Status : Client invoice has been created"
MsgBox("Saving Client Order Succeed", vbInformation, "Done")
mysqlconn.Close()
autoincrement_ClientOrderStatus()
cleartext_ClientOrderStatus()
btnSave_ClientOrderStatus.Enabled = False
btnAdd_ClientOrderStatus.Text = "Add Transaction"
READER.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
mysqlconn.Close()
Finally
mysqlconn.Dispose()
End Try
End Sub
heres my project image, maybe it can help you genospos
Here's the error when i click save
If you want to use a single access to DB you need to write a code for looping all rows to compose the query string:
This should work for you
Dim query As String = "insert into isad.invoice_table(Invoice, Clientnumber, Firstname, Lastname, ProductID, Name, Price, Qty, Description, Total, DateCreated) values "
Command = New MySqlCommand(query, mysqlconn)
For i = 0 To ListView1.Items.Count - 1
query &= "('" & txtInvoice_ClientOrderStatus.Text & "','" & txtClientNumber_ClientOrderStatus.Text.Replace("'", "\'") & "','" & txtFname_ClientOrderStatus.Text.Replace("'", "\'") & _
"', '" & txtLname_ClientOrderStatus.Text.Replace("'", "\'") & "', #ProductID" & i.ToString & ", #Name" & i.ToString & ", #Price" & i.ToString & _
", #Quantity" & i.ToString & ", #Description" & i.ToString & ", '" & txtTotal_ClientOrderStatus.Text & "',now())"
Command.Parameters.AddWithValue("#ProductID" & i.ToString, ListView1.Items(i).Text)
Command.Parameters.AddWithValue("#Name" & i.ToString, ListView1.Items(i).SubItems(1).Text)
Command.Parameters.AddWithValue("#Price" & i.ToString, ListView1.Items(i).SubItems(2).Text)
Command.Parameters.AddWithValue("#Quantity" & i.ToString, ListView1.Items(i).SubItems(3).Text)
Command.Parameters.AddWithValue("#Description" & i.ToString, ListView1.Items(i).SubItems(4).Text)
query &= ", "
Next
query = query.Substring(0, query.Length - 2)
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 "..."