I´m trying to import data into a MySQL Database, i have searched for many examples and solutions but it didn´t working and i have no idea why. Below is my vba code. I am getting runtime error 2147217900(80040e14) saying that you have an error in your sql syntax; chek the manual that corrsponds to your mysqlfor the right syntax to use near '='41282'
Sub Getdata()
Dim conn As New ADODB.Connection
Dim server_name As String
Dim database_name As String
Dim user_id As String
Dim password As String
Dim a As Long ' counter
Dim i As Long, j As Variant, k As Long
Dim sqlstr As String ' SQL to perform various actions
Dim table1 As String, table2 As String
Dim field1 As String, field2 As String
Dim field3 As String
Dim rs As ADODB.Recordset
sqlstr = "INSERT INTO" & table1 & "SET" _
& field1 & " = '" & i & "', " _
& field2 & " = '" & j & "', " _
& field3 & " = '" & k & "'"
conn.Execute sqlstr
Next a
End With
skipwrite:
End Sub
Simply, space out the table name and SET command in the concatenated string. Also, add tick marks before and after due to the reserved words used in column names (which by the way should be avoided as best practices):
sqlstr = "INSERT INTO " & table1 & " SET " _
& "`" & field1 & "` = '" & Format(i, "YYYY-MM-DD") & "', " _
& "`" & field2 & "` = '" & j & "', " _
& "`" & field3 & "` = '" & k & "';"
Also as mentioned by #Lelio, format the date to read properly into a MySQL Date column.
Date in Excel are stored as number of days between 1899-12-31 and the actual date. What you are trying to do is to store a number in a field that has a numeric format.
41282 is the number of days. So you should calculate something like:
'1899-12-31' + 'i days'
to get the date in mysql format (that by default is YYYY-MM-DD). I don't know the exact string manipulation command for VBA to get this but on the MYSQL side this should fix your error
Related
I have created a database within Microsoft access and with it a form.
I have a button attached to the form and when it's clicked I want to insert a new record into the table customerHeader.
There are four fields within that table one being an autonumber. In my SQL statement, I don't include the orderNumber since it is an autofield.
When I try to click the button and the on click event is executed, I get an error saying that Microsoft Access cannot append the records in the append query.
Any ideas, I have looked everywhere and I have not been able to find the solution.
Private Sub addOrder_Click()
Dim mySql As String
Dim rowNum As Integer
Dim recCount As Long
Dim orderNumber As Long
Dim myBool As Boolean
Dim todayDate As Date
todayDate = CDate(Date)
myBool = False
MsgBox todayDate
rowNum = Form.CurrentRecord
rowNum = CInt(rowNum - 1)
'DoCmd.GoToRecord , , acNewRec
mySql = "INSERT INTO orderHeader (orderDate,custNumber,printed) VALUES (" & todayDate & "," & rowNum & "," & myBool & ")"
DoCmd.RunSQL mySql
Me!orderNum.Requery
You don't have to much around - just use the ISO sequence for the format of the string expression for the date value:
mySql = "INSERT INTO orderHeader (orderDate,custNumber,printed) VALUES (#" & Format(todayDate, "yyyy\/mm\/dd") & "#," & rowNum & "," & myBool & ")"
However, it it's today, simply use:
mySql = "INSERT INTO orderHeader (orderDate,custNumber,printed) VALUES (Date()," & rowNum & "," & myBool & ")"
I'm trying to insert snippets of a word document into a MySQL database. I did this in Java, but I lost all formatting of the Microsoft document, so I'm now trying to do the same in VBA (I'm hoping that this will keep the formatting?!).
But to find out if it will, I need to try.. I've set up the connection and the table in MySQL but I can't insert any values. It throws up a syntax error on the "conn.Execute" line.
Sub ConnectToDataBase()
'
'
Dim conn As New ADODB.Connection
Dim Server_Name As String
Dim Database_Name As String
Dim User_ID As String
Dim Password As String
'
Dim i As Long ' counter
Dim SQLStr As String ' SQL to perform various actions
Dim table1 As String, table2 As String
Dim field1 As String, field2 As String
Dim rs As ADODB.Recordset
Dim vtype As Variant
'
Server_Name = "127.0.0.1" ' Enter your server name here -
Database_Name = "rmp" ' Enter your database name here
User_ID = "root" ' enter your user ID here
Password = "Password1" ' Enter your password here
Set conn = New ADODB.Connection
conn.Open "DRIVER={MySQL ODBC 3.51 Driver}" _
& ";SERVER=" & Server_Name _
& ";DATABASE=" & Database_Name _
& ";UID=" & User_ID _
& ";PWD=" & Password _
& ";OPTION=16427" ' Option 16427 = Convert LongLong to Int:
strSQL = "INSERT INTO parts(idParts, Part 1, Part 2, Part 3, Part 4,
Part 5) " & _
"VALUES (' " & 2 & " ' , '" & one & "' , '" & two & "' , '" &
three & "' , '" & four & "' , '" & five & "' )"
conn.Execute strSQL
Close connections
On Error Resume Next
rs.Close
Set rs = Nothing
conn.Close
Set conn = Nothing
On Error GoTo 0
End Sub
The .Net connector uses UID but the ODBC connector used by VBA uses User. I've only ever used Option=3 as well.
conn.Open "DRIVER={MySQL ODBC 3.51 Driver}" _
& ";SERVER=" & Server_Name _
& ";DATABASE=" & Database_Name _
& ";User=" & User_ID _
& ";PWD=" & Password _
& ";OPTION=16427" ' Option 16427 = Convert LongLong to Int:
You can test the connection by running a simple sql query.
strSQL = "SELECT * FROM parts;"
conn.Execute strSQL
If this throws an error, you still have an issue.
Also, in your code you have spaces either side of the 2. Is that correct?
"VALUES (' " & 2 & " ' ,
Code below, but the date in the table is not showing correctly, my computer system date is set to yyyy,mm,dd and the Access table field is selected to short date. As seen in code below the date is showing fine when debugging and stepping through the program but at the end the date in the table is shown as 1905-12-30 (Which should be 2013-12-30) any suggestions please?
InsDate = Date
**InsDate** = Format(InsDate, "yyyy,mm,dd")
AppeQry = "INSERT INTO TStockMaster ( SupplierID, PartID, UnitsID, ConditionID, " & _
"QTY, WarehouseID, BinID, RowID, ColumnID, InsDate ) VALUES ( " & SupID & "," & PrtID & "," & UntID & "," & _
CondID & "," & Qt & "," & WarehID & "," & BnID & "," & RwID & "," & ColID & "," & **InsDate** & ");"
Use a parameter query instead of concatenating values as text into an INSERT statement.
Then, when you execute the statement, and supply the parameter value, you can give it the actual Date/Time value and not be bothered with text format and date type delimiters.
Here is a simplified example. Save this query as qryTStockMasterAppend.
INSERT INTO TStockMaster (InsDate) VALUES (pInsDate);
Then your VBA code can use that saved query, supply the parameter value and execute it.
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Set db = CurrentDb
Set qdf = db.QueryDefs("qryTStockMasterAppend")
qdf.Parameters("pInsDate") = Date()
qdf.Execute dbFailOnError
We'd like to count from an Access database that has multiple tables - about 50.
We need to count from 1 column in each table that is 'QCPASS' This is a check box - if a product passed the box was checked if failed then not. We need to count both for EACH table, also allowing the user to specify a date range from a date column that exists in every table.
I've tried this with a query but I am told the query is unable to select, count and do the date range. Any VBA help would be great.
Exporting to Excel would be great, but any results would be fine. Here is the query I created that counts in a column from each table passes and failures. I can't iterate with a query either, so VBA seems the way to go:
SELECT "Table1" , Count('qcpass') AS column
FROM 5000028
GROUP BY [5000028].qcpass
union
SELECT "Table2",count('qcpass')
FROM 5000029
Group By [5000029].qcpass;
You can traverse the full TableDefs collection in your database, and create a query using VBA.
A word of warning: The TableDefs collection has the Access database system tables, so you need to skip this. A way I suggest you is to check for a specific table name prefix (it is noted in the code below).
public sub createMyBigUnionQuery()
dim db as DAO.database(), tbl as DAO.tableDef
dim strSQL as string, i as integer
set db = currentdb()
i = 1
for each tbl in db.TableDefs
if left(tbl.name, 1) = "5" then ' Check for a table name prefix
if i = 1 then
' The final spaces are important
strSQL = "select '" & tbl.Name & "' as table, count(qcpass) as column " & _
"from [" & tbl.Name & "] " & _
"group by qcpass "
else
' The final spaces are important
strSQL = strSQL & " union all " & _
"select '" & tbl.Name & "' as table, count(qcpass) as column " & _
"from [" & tbl.Name & "] " & _
"group by qcpass "
end if
i = i + 1
end if
next tbl
db.createQueryDef "qryYourFinalQuery", strSQL
db.close
exit sub
Notice that you can define any valid query you want. Take this as a hint, and tweak it to fit your specific needs.
Hope this helps you
Adressing #HansUp comment, if you need to filter your data by date, you have two options:
Include the where condition on every select created by the procedure
Include the date field in your query and group by it, and create a second query to filter the data you need from the created query.
I would personally go with option 1, and here is a sample code:
public sub createMyBigUnionQueryWithDates(d0 as date, d1 as date)
dim db as DAO.database(), tbl as DAO.tableDef
dim strSQL as string, i as integer
set db = currentdb()
i = 1
for each tbl in db.TableDefs
if left(tbl.name, 1) = "5" then ' Check for a table name prefix
if i = 1 then
' The final spaces are important
strSQL = "select '" & tbl.Name & "' as table, count(qcpass) as column " & _
"from [" & tbl.Name & "] " & _
"where rowDate between " & cDbl(d0) & " and " &cDbl(d1) & " " & _
"group by qcpass "
else
' The final spaces are important
strSQL = strSQL & " union all " & _
"select '" & tbl.Name & "' as table, count(qcpass) as column " & _
"from [" & tbl.Name & "] " & _
"where rowDate between " & cDbl(d0) & " and " &cDbl(d1) & " " & _
"group by qcpass "
end if
i = i + 1
end if
next tbl
db.createQueryDef "qryYourOtherFinalQuery", strSQL
db.close
exit sub
The reason I use cDbl(d0) is because Access dates are sensitive to regional settings, and I've had a lot of headaches dealing with it. Access (and many other Microsoft products) store dates as floating-point numbers (the integer part is the date, and the decimal part is the time).
Another word of warning: If your dates don't include time, then the between condition will work. But if they do include time, then I recommend you change the where condition to this:
"where rowDate >= " & cDbl(d0) & " and rowDate < " & cDbl(d1 + 1)"
I have a VB6 application. I have 2 recordsets having the same number of records (almost 50k). Now I have to loop 50k*50k *(number of fields). Can any one tell me the fastest way to do so?
Thanks in advance.
As others have pointed out it is not a good idea to do this client side but here are a few pointers for speeding up recordset access.
Open the recordset as forward only (adOpenForwardOnly) and if you are not writing then read only also.
Refer to the fields by number so instead of doing rs.Fields(“MyField”) you would use rs.Fields(0)
If you are writing back to the database then consider wrapping things up in a transaction to speed things up.
When looping use “Do until rs.EOF” instead of counting records.
Thats all I can think of for now but they should help a bit
There really is no fastest way to do this in vb6.
You'd use 2 for loops.
You might want to give us more details as to why you are pulling down 50k records (twice) and comparing each field. This is usually an indication that something needs to be done on the database side but was brought in to the client side to be solved.
If your two databases are the same and the only difference is the data, you could do something like this (pseudo-code):
SELECT t1.A, t2.A, t2.B, t2.B, ...
FROM t1
INNER JOIN t2 on t1.id = t2.id
WHERE (t1.A <> t2.A) OR (t1.B <> t2.B) OR ...
t1 and t2 would be your two tables. This isn't the most efficient but it would allow you to do the comparisons very easily. Also, you could get more complicated with what you show in the SELECT statement. Currently it is just a listing of both columns side by side.
Having clarified that you've got two Access databases you need to compare, the easiest is to link the two together and then compare with a query.
Right-click the white empty space, Link tables.
Locate you second DB, select the table in it.
Now you can write a query to compare the two. The data being compared is always up to date as it's being pulled through the link.
I have written code to compare and synchronize two data tables many, many times, and I've posted about it here on SO. The key is to use SQL to limit the results to the records that don't match, but the chief insight is to write your on-the-fly SQL ONE COLUMN AT A TIME. With a WHERE clause on each of your SQL statements, this will be much more efficient than any other comparison method.
Within Access, I've written this code to update one table from another. It assumes the tables have the same fields and that there's a PK field that actually identifies the same record in both tables. The code has a dependency on my SQLRun() function to actually execute the SQL, but that line could be replaced with CurrentDB.Execute if you don't want that.
Public Function UpdateTableData(ByVal strSourceTable As String, _
ByVal strTargetTable As String, ByVal strJoinField As String, _
ByRef db As DAO.Database, Optional ByVal strExcludeFieldsList As String, _
Optional ByVal strUpdatedBy As String = "Auto Update", _
Optional strAdditionalCriteria As String) As Boolean
Dim strUpdate As String
Dim rsFields As DAO.Recordset
Dim fld As DAO.Field
Dim strFieldName As String
Dim strNZValue As String
Dim strSet As String
Dim strWhere As String
strUpdate = "UPDATE " & strTargetTable & " INNER JOIN " & strSourceTable _
& " ON " & strTargetTable & "." & strJoinField & " = " _
& strSourceTable & "." & strJoinField
' if the fields don't have the same names in both tables,
' create a query that aliases the fields to have the names of the
' target table
' if the source table is in a different database and you don't
' want to create a linked table, create a query and specify
' the external database as the source of the table
' alternatively, for strTargetTable, supply a SQL string with
' the external connect string
Set rsFields = db.OpenRecordset(strSourceTable)
For Each fld In rsFields.Fields
strFieldName = fld.Name
If strFieldName <> strJoinField Or (InStr(", " & strExcludeFieldsList _
& ",", strFieldName & ",") <> 0) Then
Select Case fld.Type
Case dbText, dbMemo
strNZValue = "''"
Case Else
strNZValue = "0"
End Select
strSet = " SET " & strTargetTable & "." & strFieldName & " = _
varZLSToNull(" & strSourceTable & "." & strFieldName & ")"
strSet = strSet & ", " & strTargetTable & ".Updated = #" & Date & "#"
strSet = strSet & ", " & strTargetTable & ".UpdatedBy = " _
& STR_QUOTE & strUpdatedBy & STR_QUOTE
strWhere = " WHERE Nz(" & strTargetTable & "." & strFieldName & ", " _
& strNZValue & ") <> Nz(" & strSourceTable & "." & strFieldName _
& ", " & strNZValue & ")"
If db.TableDefs(strTargetTable).Fields(fld.Name).Required Then
strWhere = strWhere & " AND " & strSourceTable & "." _
& strFieldName & " Is Not Null"
End If
If Len(strAdditionalCriteria) > 0 Then
strWhere = strWhere & " AND " & strAdditionalCriteria
End If
Debug.Print strUpdate & strSet & strWhere
Debug.Print SQLRun(strUpdate & strSet & strWhere, dbLocal) & " " _
& strFieldName & " updated."
End If
Next fld
Debug.Print dbLocal.OpenRecordset("SELECT COUNT(*) FROM " _
& strTargetTable & " WHERE Updated=#" & Date & "# AND UpdatedBy=" _
& STR_QUOTE & strUpdatedBy & STR_QUOTE)(0) _
& " total records updated in " & strTargetTable
rsFields.Close
Set rsFields = Nothing
UpdateTableData = True
End Function
try to use the algorithm of sql., the left and right join., then apply it in vb..,
i also have the same problem with you but i try that solution and it works.., on first, it takes almost 3 hours the complete the query but when i apply the sql algo, it just takes few minis