quickly insert data to remote mysql server in vb.net - mysql

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

Related

Column count does't not match value count at row 1

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

INSERT INTO table with Foreign Key from Form

I am trying to create a Form that is used to manually enter data in certain scenarios. Most data is input from CSV files which is working fine. I have 4 tables, Part , Assembly , MachineOrder , and Job. I was able to write code for entering into the base table, Part, from the Form no problem. The issue now is entering data into the Assembly and MachineOrder tables where the Parts are being referenced by their PID autonumber field and the Assemblies are being referenced by their AID autonumbered field. I have tried many different kinds of methods to perform this of which you can see a bit of in my commented out code. What is there is what I believe to be my closest to correct code thus far with the error now being that Access asks me for the parameter value of rPID even though it is finding the value in the Dlookup function fine. I'm assuming the same is true for the rAID section as well.
Otherwise I'm getting errors of Key Violations when using the INSERT then UPDATE method you see commented out.
The form is called HOTEntry
Any advice on what my problem may be is greatly appreciated, I'm a student and this is my first time trying to use what I've learned in a professional application so any and all constructive criticism is wanted! Apologies if this is a rather specific question but I could really use the help on this since I've been working on it for two days to no avail...
My code:
Sub HOTParts2()
Dim rPID As Integer
Dim rAID As Integer
Dim dbs As DAO.Database
Dim sqlstr1 As String
Dim sqlstr2 As String
Dim sqlstr3 As String
Dim sqlstr4 As String
Set dbs = CurrentDb
'sqlstr1 = "INSERT INTO Assembly ( PID, ModelNum, ModelRev, ModelDescription ) " _
' & "SELECT (PID,Forms!HOTEntry!txtHotModel, Forms!HOTEntry!txtHotRev, Forms!HOTEntry!txtHotDes)" _
' & "FROM Part " _
' & "WHERE Part.PartName = Forms!HOTEntry!txtPartName AND Part.Config = Forms!HOTEntry!txtConfigEntry AND Part.Rev = Forms!HOTEntry!txtRevEntry"
sqlstr1 = "INSERT INTO Assembly ( ModelNum, ModelRev, ModelDescription,PID ) " _
& "VALUES (Forms!HOTEntry!txtHotModel, Forms!HOTEntry!txtHotRev, Forms!HOTEntry!txtHotDes," & "rPID" & ");"
'
'sqlstr2 = "UPDATE Assembly " _
' & "SET PID =" & rPID & " " _
' & "WHERE Assembly.ModelNum = Forms!HOTEntry!txtHotModel And Assembly.ModelDescription = Forms!HOTEntry!txtHotDes And Assembly.ModelRev = Forms!HOTEntry!txtHotRev;"
'
'sqlstr3 = "INSERT INTO MachineOrder ( AID, Serial, CustName ) " _
' & "SELECT (AID,Forms!HOTEntry!txtHotSerial, Forms!HOTEntry!txtHotCust)" _
' & "FROM Assembly" _
' & "WHERE Assembly.Model=Forms!HOTEntry!txtHotModel And ModelDescription= Forms!HOTEntry!txtHotDes And ModelRev = Forms!HOTEntry!txtHotRev; "
sqlstr3 = "INSERT INTO MachineOrder (Serial, CustName, AID ) " _
& "VALUES (Forms!HOTEntry!txtHotSerial, Forms!HOTEntry!txtHotCust," & "rAID" & ");"
'
'sqlstr4 = "UPDATE MachineOrder " _
' & "SET AID =" & rAID & " " _
' & "WHERE AID IS NULL;"
rPID = DLookup("PID", "Part", "PartName = " & "'" & Forms!HOTEntry!txtPartName & "'" & " And " & "Config = " & "'" & Forms!HOTEntry!txtConfigEntry & "'" & " And " & "Rev = " & "'" & Forms!HOTEntry!txtRevEntry & "'")
DoCmd.RunSQL sqlstr1
'DoCmd.RunSQL sqlstr2
rAID = DLookup("AID", "Assembly", "ModelNum = " & "'" & Forms!HOTEntry!txtHotModel & "'" & " And " & "ModelDescription = " & "'" & Forms!HOTEntry!txtHotDes & "'" & " And " & "ModelRev = " & "'" & Forms!HOTEntry!txtHotRev & "'")
DoCmd.RunSQL sqlstr3
'DoCmd.RunSQL sqlstr4
End Sub
Well, if you want to use the looked up rPID and rAID in a query, you need to do more than just set them in VBA. You can either manually fill them in in your SQL statement, use a parameter and a QueryDef and fill in the parameter in your QueryDef, or put the DLookUp inside your SQL statement.
Going with the first approach here, only unquoted rPID in your initial statement, and put it after rPID was set.:
rPID = DLookup("PID", "Part", "PartName = " & "'" & Forms!HOTEntry!txtPartName & "'" & " And " & "Config = " & "'" & Forms!HOTEntry!txtConfigEntry & "'" & " And " & "Rev = " & "'" & Forms!HOTEntry!txtRevEntry & "'")
sqlstr1 = "INSERT INTO Assembly ( ModelNum, ModelRev, ModelDescription,PID ) " _
& "VALUES (Forms!HOTEntry!txtHotModel, Forms!HOTEntry!txtHotRev, Forms!HOTEntry!txtHotDes," & rPID & ");"
DoCmd.RunSQL sqlstr1

Open Report Use Three Combobox Filter

I have 3 combobox to filter data, then i want to open in command button to print preview..
Problems I have if i used 2 combobox it works but when i used three combobox the report is blank...there's any problems with the code?? here's the code i used :
Dim strWhereCondition As String
strWhereCondition = "[month] = '" & Me.cbmonth.Value _
& "' and [Works] = '" & Me.cbwork.Value _
& "' and [Works] = '" & Me.cbwork2.Value & "'"
Debug.Print strWhereCondition
DoCmd.OpenReport "Month List", View:=acViewPreview, _
WhereCondition:=strWhereCondition
and the requery for my form
SELECT *
FROM MyTable
WHERE (month = Forms!nameForm!cbmonth
OR Forms!MeForm!cbwork IS NULL)
And (works = Forms!nameForm!cbwork
OR Forms!nameForm!cbwork IS NULL)
AND (works = Forms!nameForm!cbwork2
OR Forms!nameForm!cbwork2 IS NULL);
can anyone help?
Month is a number, so try:
strWhereCondition = "[month] = " & Me.cbmonth.Value _
& " and [Works] = '" & Me.cbwork.Value _
& "' and [Works] = '" & Me.cbwork2.Value & "'"
Edit: Month is text.
However, [Work] is supposed to match two potentially different values:
& "' and [Works] = '" & Me.cbwork.Value _
& "' and [Works] = '" & Me.cbwork2.Value & "'"
Should most likely be:
& "' and [Works] = '" & Me.cbwork.Value _
& "' and [SomeOtherField] = '" & Me.cbwork2.Value & "'"

CheckIfExist. If exist don't insert the data, if not insert the data

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

MYSQL-Access-Macro Error Unknown column in field list

I am trying to run an Excel macro that imports data from a csv file into an Access database, MySQL front end. The macro code is not new-we've been using this for a couple of years, the table in the Access DB is not new, and the csv files with which the data is used to be brought into the Access table is also unchanged (meaning same rows, same data types).
I am stumped as the error appears to be something of an anomaly and I have tried several fixes to correct the error. I have attached a copy of the error as well as the code below. The issue with the column referenced below as well error message attached, "itemcode", this column is in the database.
Clearly, there is something that I am missing. Any insights are greatly appreciated. Thank you.
'Read in Current .csv file
'Data Services
NumRows = Application.CountA(Range("A:A"))
For iCount = 1 To NumRows
Dim InstData(11)
InstData(1) = Range("A" & iCount) 'Date
invoiceDate = Format(InstData(1), "yyyy/mm/dd")
InstData(2) = Range("B" & iCount) 'Invoice Number
InstData(3) = Range("C" & iCount) 'names
flname() = Split(InstData(3), ",")
lname = flname(0)
fname = flname(1)
InstData(4) = Range("D" & iCount) 'Address1
InstData(5) = Range("E" & iCount) 'Address2
InstData(6) = Range("F" & iCount) 'City
InstData(7) = Range("G" & iCount) 'State
InstData(8) = Format(Range("H" & iCount), "00000") 'postal code
InstData(9) = Range("I" & iCount) 'phone
InstData(10) = Range("J" & iCount) 'email
InstData(11) = Range("K" & iCount) 'amount
Set conn = New ADODB.Connection
Set rec = New ADODB.Recordset
conn.Open "Dsn=HERIpub"
rec.Open ("Insert into tbl_Invoice (invoiceNumber,invoiceDate,invoiceAmount,invoiceDescription,invoiceFAU,invoiceCostCenter,invoiceProject,itemcode,invoicecFName,invoicecLName, invoicecAddr1, invoicecAddr2, invoicecCity, invoicecState, invoicecZIP, invoicecEmail, invoicecPhone) Values ('" & InstData(2) & "','" & invoiceDate & "','" & InstData(11) & "','Data Services','T6','T6','DATASL','40070DATASL','" & fname & "'" & ",'" & lname & "','" & InstData(4) & "', '" & InstData(5) & "', '" & InstData(6) & "', '" & InstData(7) & "', '" & InstData(8) & "', '" & InstData(10) & "', '" & InstData(9) & "')"), conn
macro error
Look at the variable fname , there you have redundant " & " . I think it should be:
rec.Open ("Insert into tbl_Invoice (invoiceNumber,invoiceDate,invoiceAmount,invoiceDescription,invoiceFAU,invoiceCostCenter,invoiceProject,itemcode,invoicecFName,invoicecLName, invoicecAddr1, invoicecAddr2, invoicecCity, invoicecState, invoicecZIP, invoicecEmail, invoicecPhone) Values ('" & InstData(2) & "','" & invoiceDate & "','" & InstData(11) & "','Data Services','T6','T6','DATASL','40070DATASL','" & fname & "','" & lname & "','" & InstData(4) & "', '" & InstData(5) & "', '" & InstData(6) & "', '" & InstData(7) & "', '" & InstData(8) & "', '" & InstData(10) & "', '" & InstData(9) & "')"), conn
Tell me if I'm right, or mark a vote up!