I'm having a problem about my code, i already tried to put the specified table for each column, In which part of my code was having a problem?
clientid = clientid.Substring(0, 3)
rnd = random.Next(100, 999)
clientid = clientid & "-" & Format(Now, "MMdd") & "-" & rnd
query = "SELECT COUNT(*) FROM tbl_clients WHERE clients_Record_Num ='" & clientid & "'"
sqlcmd = New MySqlCommand(query, conn)
chkclientid = sqlcmd.ExecuteScalar()
While chkclientid > 0
clientid = clientid.Substring(0, 3)
rnd = random.Next(100, 999)
clientid = clientid & "-" & Format(Now, "MMdd") & "-" & rnd
query = "SELECT COUNT(*) FROM tbl_clients WHERE clients_record_num ='" & clientid & "'"
sqlcmd = New MySqlCommand(query, conn)
chkclientid = sqlcmd.ExecuteScalar()
End While
query = "Insert into tbl_clients(clients_record_num,clients_client_id,clients_name,clients_contact_number,clients_address,clients_industry,clients_status,clients_delegate,clients_notes) values ('" & clientid.Substring(0, 3) &_ "-" & dttime & "-" & rnd &_ "','" & clientid & _
"', '" & txtClientName.Text & "','" & txtClientContactNum.Text & "','" & txtClientAddress.Text & _
"','" & cmbIndustry.Text & "', '" & cmbStatus.Text & "', '" & cmbDelegate.Text & "','" & txtNotes.Text & "','0')"
sqlCommand.Connection = conn
sqlCommand.CommandText = query
sqlCommand.ExecuteNonQuery()
As #jmcilhinney commented, change your insert query to use parameters as it will be easier to read and to ensure that the number of values matches the number of columns.
Here's some 'template' code for you to expand on:
Dim InsertCmdText As String =
"Insert into tbl_clients(clients_record_num,clients_client_id,clients_name,clients_contact_number,clients_address,clients_industry,clients_status,clients_delegate,clients_notes) " &
"values (#clients_record_num,#clients_client_id,#clients_name,#clients_contact_number,#clients_address,#clients_industry,#clients_status,#clients_delegate,#clients_notes)"
Dim SqlConnectionString As String = "Your Connection Info"
Using cmd As New SqlCommand(InsertCmdText, New SqlConnection(SqlConnectionString))
Try
cmd.Parameters.AddWithValue("#clients_record_num", "Value Needed")
cmd.Parameters.AddWithValue("#clients_client_id", "Value Needed")
cmd.Parameters.AddWithValue("#clients_name", "Value Needed")
'repeat above for all params
cmd.Connection.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
'Handle your exception
Finally
cmd.Connection.Close()
End Try
End Using
Alternatively use Parameters.Add instead of AddWithValue. For discussion on merits of each, see SqlCommand Parameters Add vs. AddWithValue
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.
I have a problem on how to insert data into two different table. So my requirements is this.
Under Group Details, The user need to click all the needed information on the dropdown menu and input on the textbox of the table grid view before clicking the ADD Link, after this the page will load displaying the Added Job Title and business group details. The user is allowed to input as many Job title as the user want.
I already finished the table but I have problems in saving the data that I input.
So my first table looks like this Before
and I edit it and this is my table Now
So my problem is this, in my database i have two table. One is EMPGROUP_TBL with columns SEQID, masterID, Business Unit, Division, Sub-Division etc. and the other is EMP_MASTERTBL with columns MasterID, Name, LastName, Jobtitle.
Now everytime I click Add link the jobtitle will not be able to save in the EMP_MASTERTBL so I create a code in VB.Net that will update the EMP_MASTERTBL table when I click the add button under Group Details.
Here's my codes.
If UpdateInsDelRecord("INSERT INTO EMPGROUP_TBL (MASTERID, BUSINESS_UNIT, " & _
"DIVISION, SUB_DIVISION, CLASSIFICATION, SUB_CLASSIFICATION) VALUES " & _
"('" & HandleQuote(Me.lblval_Empid.Text) & "', " & _
"'" & Me.ddl_BusinessUnit.SelectedValue.ToString() & "' ," & _
"'" & val_division & "' ," & _
"'" & val_subdivision & "' ," & _
"'" & Me.ddl_Classification.SelectedValue.ToString() & "' ," & _
"'" & Me.ddl_SubClassification.SelectedValue.ToString() & "')" & _
";" & _
"UPDATE EMP_MASTERTBL SET JOBTITLE = '" & Me.txtJobtitle.Text & "' " & _
"WHERE MASTERID = '" & Me.lblval_Empid.Text & "'") = True Then
Return True
Response.Redirect("eHR_EmpMaintenance.aspx")
Else
Return False
End If
But the user must be able to add as many as Jobtitle and EMPGROUP_TBL details as the user want. So I'm thinking that I'll just write another query for that? How can I add the Group Details and be able to add as many as Jobtitle as the user want?
CheckIfExist
I figured maybe I could use the CheckIfExist and if the employee has an existing data to the jobtitle, business unit, division, sub-division, classification and sub-classification similar to the one that you will add, the messagebox will show that the data already exist. If no data found then it will be able to add the details under the employee's group details. And if you input similar jobtitle but different business unit etc. the data will just be updated and vice versa.
Here's what my code for this.
Function SaveUserGroup() As Boolean
Try
Dim jobtitle As String = Me.txtJobtitle.Text
Dim businessunit As String = Me.ddl_BusinessUnit.SelectedValue
Dim division As String = Me.ddl_Division.SelectedValue
Dim subdivision As String = Me.ddl_SubDivision.SelectedValue
Dim classification As String = Me.ddl_Classification.SelectedValue
Dim subclassification As String = Me.ddl_SubClassification.SelectedValue
Dim CheckMasterTblIfExist As Boolean
Dim CheckGroupTblIfExist As Boolean
Dim insrtResult As Boolean
Dim seqid As String = Me.lblSEQID.Text
Dim emp_id As String = Request.QueryString("emp_id")
If jobtitle <> "" And businessunit <> "Please Select" And division <> "Please Select" And subdivision <> "Please Select" And classification <> "Please Select" And subclassification <> "Please Select" Then
CheckMasterTblIfExist = CheckRecord("SELECT MASTERID, JOBTITLE FROM EMP_MASTERTBL WHERE JOBTITLE = '" & jobtitle & "' AND MASTERID = '" & emp_id & "' ")
CheckGroupTblIfExist = CheckRecord("SELECT * FROM EMPGROUP_TBL WHERE BUSINESS_UNIT = '" & businessunit & "' AND DIVISION = '" & division & "' AND SUB_DIVISION = '" & subdivision & "' AND CLASSIFICATION = '" & classification & "' AND SUB_CLASSIFICATION = '" & subclassification & "' AND MASTERID = '" & emp_id & "' AND SEQID = '" & seqid & "'")
If Not CheckMasterTblIfExist And CheckGroupTblIfExist Then
insrtResult = UpdateInsDelRecord("UPDATE EMP_MASTERTBL SET JOBTITLE = '" & jobtitle & "' " & _
"WHERE MASTERID = '" + Me.lblval_Empid.Text + "'" & _
";" & _
"INSERT INTO EMPGROUP_TBL(MASTERID, BUSINESS_UNIT, " & _
"DIVISION, SUB_DIVISION, CLASSIFICATION, SUB_CLASSIFICATION) VALUES " & _
"('" & HandleQuote(Me.lblval_Empid.Text) & "', " & _
"'" & businessunit & "' ," & _
"'" & division & "' ," & _
"'" & subdivision & "' ," & _
"'" & classification & "' ," & _
"'" & subclassification & "')")
If Not insrtResult Then
MessageBox("alert('Error Ocurred While Inserting a Data.')")
Else
MessageBox("alert('Successfully Added.')")
End If
Else
MessageBox("alert('Data Already Exist.')")
End If
End If
Catch ex As Exception
MessageBox("Error Ocurred while Inserting a data")
Throw
End Try
End Function
I haven't been completed the code yet. I'm in the adding if there's no data and my problem is that the messagebox keeps on telling me that the data already exist even if there's still no employee's group details that added. Please help me with this.
begin tran
if exists (select * from table with (updlock,serializable) where key = #key)
begin
update table set ...
where key = #key
end
else
begin
insert into table (key, ...)
values (#key, ...)
end
commit tran
you can use like this
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)
Try
MySqlConn.Open()
Dim Query = "Select * From venuesdb.cost where EventDate >= ('" & DateTimePicker1.Text & "') AND =< ('" & DateTimePicker2.Text & "')"
Command = New MySqlCommand(Query, MySqlConn)
SQLDataAdapter.SelectCommand = Command
SQLDataAdapter.Fill(DatabaseDatSet)
Bindsource.DataSource = DatabaseDatSet
DataGridView1.DataSource = Bindsource
SQLDataAdapter.Update(DatabaseDatSet)
MySqlConn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
MySqlConn.Dispose()
I keep getting error saying that there is a SQL error here '>= ('" & DateTimePicker2 & " ')'
Your syntax is incorrect, you can either use between without <= and >=(mind symbol sequence in the operators):
Dim Query = "select *
from venuesdb.cost
where EventDate between '" & DateTimePicker1.Text & "' AND '" & DateTimePicker2.Text & "'"
or specify field each time you specify condition:
Dim Query = "select *
from venuesdb.cost
where EventDate >= '" & DateTimePicker1.Text & "' AND EventDate <= '" & DateTimePicker2.Text & "'"
You missed a EventDate in your query. Change your code to this:
Dim Query = "Select * From venuesdb.cost where EventDate >= ('" & DateTimePicker1.Text & "') AND EventDate =< ('" & DateTimePicker2.Text & "')"
Also, you should use parameters in your query to avoid SQL-injection attacks. You can read more about it in this SO question.
I have small application in vb.net
I have one table in msaccess, which is having around 20,000 records,
now, I want to insert these records to remote server of mysql,
I tried as below code, it takes around 3-4 hours to insert data,
Can anyone show me faster way to insert data, i will be very glad..
dst in code is having all records from ms Access
For i As Integer = 0 To dst.Tables(0).Rows.Count - 1
mycmd.Connection = mycn
str = "INSERT INTO tblstudentresults(department_desc, grade, roll_no, name, course_code, course_desc, examination_type, total_marks, obtained_marks)"
/*'str = str & " VALUES('" & cname & "','" & sdr("grade").ToString() & "','" & sdr("st_code").ToString() & "','" & sdr("stName").ToString() & "','" & sdr("Subject_code").ToString() & "','" & sdr("Subject").ToString() & "','" & sdr("ExamTitle").ToString() & "','" & sdr("Maxmark").ToString() & "','" & sdr("score").ToString() & "')" -- Added non-VB comment here to improve readability */
str = str & " VALUES('" & cname & "', '" & dst.Tables(0).Rows(i)("grade").ToString() & "', '" & dst.Tables(0).Rows(i)("st_code").ToString() & "', '" & dst.Tables(0).Rows(i)("stName").ToString() & "', '', '" & dst.Tables(0).Rows(i)("Subject").ToString() & "', '" & dst.Tables(0).Rows(i)("ExamTitle").ToString() & "', '" & dst.Tables(0).Rows(i)("Maxmark").ToString() & "', '" & dst.Tables(0).Rows(i)("score").ToString() & "')"
mycmd.CommandText = str
mycmd.ExecuteNonQuery()
next
It might be faster to construct a multiple-row insert in one large string (or maybe chunks of, say 500 rows), then run the entire insert statement in a single call, something roughly like the following:
Dim firstRow as Boolean = True
str = "INSERT INTO tblstudentresults(...) VALUES"
For i As Integer = 0 To dst.Tables(0).Rows.Count - 1
' Only insert comma after first row, so we don't have comma at the end.
If Not firstRow Then str = str & ","
str = str & "('" & cname & "','" ...
firstRow = False
Next
mycmd.Connection = mycn
mycmd.CommandText = str
mycmd.ExecuteNonQuery()