This code:
db = "C:\Dokumente und Einstellungen\hom\Anwendungsdaten\BayWotch4\Neuer Ordner\baywotch.db5"
TextExportFile = "C:\Dokumente und Einstellungen\hom\Anwendungsdaten\BayWotch4\Neuer Ordner\Exp.txt"
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
cn.Open _
"Provider = Microsoft.Jet.OLEDB.4.0; " & _
"Data Source =" & db
strSQL = "SELECT * FROM tblAuction1"
rs.Open strSQL, cn, 3, 3
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.CreateTextFile(TextExportFile, True, True)
a = rs.GetString
f.WriteLine a
f.Close
generates a tab delimited file, however it is not suitable for importing into mysql. I would like it to generate a file similar to a file produced by an access macro, which can be seen here:
http://www.yousendit.com/download/TTZtWmdsT01kMnVGa1E9PQ
The file produced by the vbscript is here:
http://www.yousendit.com/download/TTZtWmdsT00wVWtLSkE9PQ
I would also like to know why the file sizes differ by 50k or so.
Edit: The result from the vbscript file uses newline characters that are not recognized by notepad, so the above looks substantially messier when viewed. The macro does not seem to be exporting the html code, which explains why it is a smaller file, however the vbscript does not appear to be tab delimited, as it will not import into mysql.
Edit: the files look ok under a linux system, so it could be something to do with windows handling. However it is still not correct.
Both files contain what looks like tab-delimited data as well as HTML code (generated by some MS Office app, by the looks of it). Does tblAuction1 store any OLE Objects? Perhaps when you're exporting those objects it's exporting the file contents?
It looks like an encoding issue to me. I see that you are passing the Unicode parameter when you create the text file, but there is clearly an encoding difference between the two files.
What is the goal of this project? What is the purpose of creating the file? If you are just looking to move data from Access to MySQL, why not do it directly with something like this
Const Access = "Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;Data Source=C:\Dokumente und Einstellungen\hom\Anwendungsdaten\BayWotch4\Neuer Ordner\baywotch.db5"
Const SQLServer = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Data Source=.\SQLEXPRESS"
Dim arrFields
Set SQLConn = CreateObject("ADODB.Connection")
WITH SQLConn
.ConnectionString = SQLServer
.Open
End WITH
Set AccessConn = CreateObject("ADODB.Connection")
WITH AccessConn
.ConnectionString = Access
.Open
End WITH
Set SQLRS = CreateObject("ADODB.Recordset")
WITH SQLRS
.CursorType = 3
.LockType = 3
End WITH
Set AccessRS = CreateObject("ADODB.Recordset")
WITH AccessRS
.ActiveConnection = AccessConn
.CursorType = 3
.LockType = 3
End WITH
strSQL = "SELECT * FROM tblAuction1"
AccessRS.Open strSQL
If AccessRS.RecordCount <> 0 Then
AccessRS.MoveFirst
ReDim arrFields(AccessRS.Fields.Count)
Do Until AccessRS.BOF OR AccessRS.EOF
For i = 0 To AccessRS.Fields.Count - 1
If AccessRS.Fields(i).Type = 202 Then
arrFields(i) = Chr(39) & AccessRS.Fields(i).Value & Chr(39)
Else
arrFields(i) = AccessRS.Fields(i).Value
End If
Next
strSQL1 = "INSERT INTO {Table in mySQL} VALUES("
For j = 1 To UBound(arrFields) - 2
strSQL1 = strSQL1 & arrFields(j) & ","
Next
strSQL1 = strSQL1 & arrFields(UBound(arrFields) - 1) & ")"
SQLRS = SQLConn.Execute(strSQL1)
AccessRS.MoveNext
Loop
Else
MsgBox "No records found"
End If
This will add all of the records returned by the recordset to a table in an SQLExpress database,it should not be difficult to tweak to your needs (if your needs are transferring data from one database to another).
Related
I'm developing a VB Script for WinCC RunTime on a SIMATIC PC station to export the historical data of my project once a month. I'm setting up an ADO connection and querying the results into a recordset that I'm printing to a csv. I'm having several problems:
The recordset returns a ValueID, I want to be able to find the tagname that corresponds to it and write it to the csv.
I am limited to 20 tags per query, but I want to export 30 tags.
Running a for loop of the query for each tag produces nothing.
My code currently looks like this:
Dim fso
Dim f
Dim ts
Dim path
Dim TimeStamp
Dim Pro
Dim DSN
Dim DS
Dim ConnString
Dim MachineNameRT
Dim DSNRT
Dim Conn
Dim RecSet
Dim Command
Dim CommandText
TimeStamp = localDateFormat(Now)
path = "C:\Logs\Test1_" & TimeStamp & ".csv"
Set fso = CreateObject("Scripting.FileSystemObject")
If Not fso.FileExists(path) Then
fso.CreateTextFile(path)
Else
MsgBox "File already exist:" & vbCrLf & path
Exit Sub
End If
Set f = fso.GetFile(path)
Set ts = f.OpenAsTextStream(2,-2)
Set MachineNameRT = HMIRuntime.Tags("#LocalMachineName")
Set DSNRT = HMIRuntime.Tags("#DatasourceNameRT")
Pro="Provider=WinCCOLEDBProvider.1;"
DSN="Catalog=" & DSNRT.Read & ";"
DS= "Data Source=" & MachineNameRT.Read & "\WinCC"
ConnString = Pro + DSN + DS
Set Conn = CreateObject("ADODB.Connection")
Conn.ConnectionString = ConnString
Conn.CursorLocation = 3
Conn.open
Set Command = CreateObject("ADODB.Command")
Command.CommandType = 1
Set Command.ActiveConnection = Conn
ts.WriteLine ("Tag-Name;ValueID;Date/Time;Process-Value")
CommandText="Tag:R,'Data_Log\TempTran','0000-01-00 00:00:00.000','0000-00-00 00:00:00.000'"
Command.CommandText=CommandText
Set RecSet = Command.Execute
RecSet.MoveFirst
Do While Not RecSet.EOF
ts.WriteLine ("TempTran;" & RecSet.Fields("ValueID").Value & ";" & RecSet.Fields("TimeStamp").Value & ";" & RecSet.Fields("RealValue").Value)
RecSet.MoveNext
Loop
ts.Close
RecSet.Close
Set RecSet=Nothing
Set Command = Nothing
Conn.Close
Set Conn = Nothing
Set fso = Nothing
Set f = Nothing
Set ts = Nothing
What I need as an end result is a CSV file that displays like this
Tag-Name;ValueID;Date/Time;Process-Value;
TempTran;1;dd/mm/yyyy hh:mm:ss;xxx.xxx;
TempTran;1;dd/mm/yyyy hh:mm:ss;xxx.xxx;
PresTran;2;dd/mm/yyyy hh:mm:ss;xxx.xxx;
.
.
.
.
LimitSwt;30;dd/mm/yyyy hh:mm:ss;xxx.xxx;
LimitSwt;30;dd/mm/yyyy hh:mm:ss;xxx.xxx;
LimitSwt;30;dd/mm/yyyy hh:mm:ss;xxx.xxx;
Q1:
The ValueID and tagname is in the Table "Archive" if the database is linked to connectivity pack.
SELECT [ValueID]
,[ValueName]
FROM [CC_ExternalBrowsing].[dbo].[Archive]
Otherwise you can find the valueId in the CS database
Runtime is in this case "CC_GruppLar_15_05_06_10_35_08R", its the last 'R' that indicate "runtime", remove this and you are in the construction database(CS):
Varname = the given name
procvarname= the tag that is archived.
TLGTAGID = The ValueID
SELECT [VARNAME]
,[PROCVARNAME]
,[TLGTAGID]
FROM [CC_GruppLar_15_05_06_10_35_08].[dbo].[PDE#TAGs]
Q3:
perhaps this note about months in the fine help can help? or try to verify using that there is data present for this tag. I think its a good idea to test the SQL statements using the given tool "Microsoft SQL Manager Studio", that's faster then using excel...
Note
Enter a relative period you want to query in a linked archive database using the following format:
0000-00-DD hh:mm:ss.msc
If you indicate the time frame in months, the content can be faulty, because a month can have 28 to 31 days.
Example for reference:
Exporting Archive Data with the Aid of the SIMATIC WinCC/Connectivity Pack (OLE DB Provider)
https://support.industry.siemens.com/cs/se/en/view/38132261
This is kind of a follow-up post to this question.
I am trying to put data from a .csv into a .mdb (MS Access 2000).
This script works perfectly fine if the DB is stored on my hard drive, but it is on a different drive I access over a network. I have full rights there and I can insert new data sets by hand without any problems.
'There are several other Subs in this .hta-file
'these two are specified along with some other public variables
'in the beginning
Const adOpenStatic = 3
Const adLockOptimistic = 3
Sub CSVImport
connStr = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=S:\folderpath with blanks ß and ,commas\somedatabase.mdb"
'Define object type
Set objConn = CreateObject("ADODB.Connection")
Set objRecordSet = CreateObject("ADODB.Recordset")
'Open Connection
objConn.open connStr
objRecordSet.Open "SELECT * FROM SomeTable", _
objConn, adOpenStatic, adLockOptimistic
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("P:\someFile.csv")
Do Until objFile.AtEndOfStream
strVKBL_Stamm = objFile.ReadLine
arrVKBL_Stamm = Split(strVKBL_Stamm, ";")
objRecordSet.AddNew
objRecordSet("ID") = arrVKBL_Stamm(0)
objRecordSet("LastName") = arrVKBL_Stamm(1)
objRecordSet("Date") = CDate(arrVKBL_Stamm(2))
objRecordSet("More") = arrVKBL_Stamm(...)
objRecordSet("andMore") = arrVKBL_Stamm(...)
objRecordSet.Update
Loop
MsgBox "All done"
Set objRecordSet = Nothing
Set objFSO = Nothing
Set objFile = Nothing
Set objConn = Nothing
End Sub
My .csv-File looks like this:
50009900;Doe;01.01.12;foo;bar
I don't get any errors, while the script is running. I checked the strings stored in arrVKBL_Stamm(...) and they all are alright. My last MsgBox pops up, the script stops, nothing happened in my DB.
Any thoughts?
I replied on your first thread but I want to reiterate here that you are reinventing a wheel that works very well as it is. I wouldn't recommend using VBScript for what you are trying to do. You could write this same code in VBA directly inside of Access itself. You don't even need to do that because SAP uses a standard database engine in the back end. You can set up linked tables that pull directly from SAP in to Access. No export\import. It's a live table.
I hate to give you "don't do that" as an answer but that is most definitely the correct answer for you.
So use a linked table directly to SAP or move this code in to Access VBA and run it from there.
This line jumps out at me for being a static recordset adOpenStatic as that won't allow record updates on the DB, only the client side recordset:
objRecordSet.Open "SELECT * FROM SomeTable", objConn, adOpenStatic, adLockOptimistic
A dynamic or another type of cursor is what you would need:
objRecordSet.Open "SELECT * FROM SomeTable", objConn, adOpenDynamic, adLockOptimistic
Every month I have to UPDATE my MS Access db from approximately 30 excel files. They have all the same structure and format. I try to modify this code several times to update each tables in my db in once but i didn't succeed. (found in this forum)
I have 3 questions:
How is it possible to say to the vba code to look at this range in the excel template which correspond to this column in the MS Access db?
How can i make this vba code update all the tables in once based on the Primary Key?
Then, Is it possible to select the Folder where all these excel files are and the code will loop through all files?
Public Sub UpdatePriceList()
Dim cn As ADODB.Connection, rs As ADODB.Recordset
Dim sProduct As String, sVariety As String, cPrice As Variant
' connect to the Access database
Set cn = New ADODB.Connection
cn.Open "Provider=Microsoft.ACE.OLEDB.12.0; " & _
"Data Source=C:\Users\Gord\Desktop\Database1.accdb;"
' open a recordset
Set rs = New ADODB.Recordset
rs.Open "PriceList", cn, adOpenKeyset, adLockOptimistic, adCmdTable
Range("A2").Activate ' row 1 contains column headings
Do While Not IsEmpty(ActiveCell)
sProduct = ActiveCell.Value
sVariety = ActiveCell.Offset(0, 1).Value
cPrice = ActiveCell.Offset(0, 2).Value
rs.Filter = "product='" & sProduct & "' AND variety='" & sVariety & "'"
If rs.EOF Then
Debug.Print "No existing record - adding new..."
rs.Filter = ""
rs.AddNew
rs("product").Value = sProduct
rs("variety").Value = sVariety
Else
Debug.Print "Existing record found..."
End If
rs("price").Value = cPrice
rs.Update
Debug.Print "...record update complete."
ActiveCell.Offset(1, 0).Activate ' next cell down
Loop
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub
thank you in advance!
If you know how to deal with a single excel file and convert it to acess table and all the rest of file will be treated the same way. You can use a bot which will automate the task and do it quickfast. You just have to give it the "instruction" how to deal with single file and it will do the rest.
The instruction can be as simple as a notepad file with table containing the mouse positions and the stroken keyboards key necessary to deal with one file.
You may use "Autoit V3 script"
I am trying to read JPG images from MS-Access database using the following code in classic ASP:
Response.Expires = 0
Response.Buffer = TRUE
Response.Clear
Response.ContentType = "image/jpg"
Set cn = Server.CreateObject("ADODB.Connection")
cn.Open "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & Server.MapPath("/database/database.mdb")
sqlString = "Select * from tblBusinessImages where fldID = " & request.querystring("id")
Set rs = cn.Execute(sqlString)
Response.BinaryWrite rs("fldImageData")
Response.End
But I keep getting an error telling that the browser can't read or display the image.
The database field 'tblBusinessImages' is an OLE field, and the image is saved into it by copy-paste, only for testing purpose at this time (could this be a wrong way?)
Now I know that MS-Access saves extra data in the BLOB object (as MSDN says here:
If any extraneous information is contained in the BLOB data, this will
be passed by this script, and the image will not display properly.
This becomes important when you realize that most methods of placing
images into BLOB fields place extra information in the form of headers
with the image. Examples of this are Microsoft Access and Microsoft
Visual FoxPro. Both of these applications save OLE headers in the BLOB
field along with the actual binary data.
)
My question is how do I read the RAW image data from a BLOB without the extra data/headers that MS-Access saves?
Thanks.
After a day of work I realized what the problem was: The problem was in the way the picture was saved to the database (manually).
In order to save images to database, the following code should be used:
Dim fileName
Dim conn
Dim rsTemp
Dim fldID
Dim sSQL
Dim mystream
Set mystream = Server.CreateObject("ADODB.Stream")
mystream.Type = 1
mystream.Open
mystream.LoadFromFile "D:\Desktop\My Downloads\compose1.jpg"
Set conn = Server.CreateObject("ADODB.Connection")
Set rsTemp = Server.CreateObject("ADODB.Recordset")
conn.Open "DRIVER=Microsoft Access Driver (*.mdb);DBQ=" & Server.MapPath("/database/database.mdb")
sSQL = "Select fldImageData from tblBusinessImages where fldID = 1;"
rsTemp.Open sSQL, conn, 3, 3
rsTemp.Fields("fldImageData").AppendChunk mystream.Read
rsTemp.Update
rsTemp.Close
set mystream = nothing
And in order to read an image from MS-Access database, this code should be used:
Dim conn
Dim rsTemp
Dim sSQL
Dim fldID
fldID = Request.QueryString("id")
If Not fldID = "" And IsNumeric(fldID) Then
Set conn = Server.CreateObject("ADODB.Connection")
Set rsTemp = Server.CreateObject("ADODB.Recordset")
conn.Open "DRIVER=Microsoft Access Driver (*.mdb);DBQ=" & Server.MapPath("/database/database.mdb")
sSQL = "Select * from tblBusinessImages where fldID = " & request.querystring("id")
rsTemp.Open sSQL, conn, 3, 3
If Not rsTemp.EOF Then
Response.ContentType = "image/jpeg"
Response.BinaryWrite rsTemp("fldImageData")
Else
Response.Write("File could not be found")
End If
rsTemp.Close
conn.Close
Set rsTemp = Nothing
Set conn = Nothing
Else
Response.Write("File could not be found")
End If
This way the image data will be saved as Long Binary Data in the OLE field in the database. When read, it will be posted to the browser as a readable image data.
I have an Access database which I would like to export to a text file. I have a schema defined within Access, and currently use a macro to export it. I would like to use VBScript to always append the result of a query to the same file. If it is not possible to use my defined schema, I only need the fields to be comma separated and enclosed by the ", and the text file must be in UTF-8 format.
I found the following code snippet, but I am unsure how to adopt it for my needs.
db = "C:\Docs\LTD.mdb"
TextExportFile = "C:\Docs\Exp.txt"
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
cn.Open _
"Provider = Microsoft.Jet.OLEDB.4.0; " & _
"Data Source =" & db
strSQL = "SELECT * FROM tblMembers"
rs.Open strSQL, cn, 3, 3
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.CreateTextFile(TextExportFile, True)
a = rs.GetString
f.WriteLine a
f.Close
DIRECTION (2)
This is some VBA, run from the Access database:
Sub InsertRecs()
Set db = CurrentDb
'DSN=Suitable system DSN for MySQL
'Then, depending on your set up, you can incude:
'Database=DBName;
'Trusted_Connection=Yes;
'NameOfMySQLTable
strSQL = "INSERT INTO [ODBC;DSN=baywotch;].tblAuction Select * FROM tblAuction;"
db.Execute strSQL, dbFailOnError
End Sub
This is the same thing, but in VBScript, using DAO:
Dim objEngine
Dim objWS
Dim objDB
Dim db: db = "C:\Docs\baywotch.db5"
Set objEngine = wscript.CreateObject("DAO.DBEngine.36")
Set objDB = objEngine.OpenDatabase(db)
objDB.Execute "INSERT INTO [ODBC;DSN=baywotch].[tblAuction] SELECT * FROM tblAuction;"
DIRECTION (1)
I suggest a completely different direction, and that is to let MySQL do the work:
MySQL Migration Toolkit
I tested this against your database, and it appears to import correctly, only takes a few minutes, and will generate all sorts of reusable scripts and so on.
If you are having problems with the set-up of MySQL, you may wish to read:
9.1.4. Connection Character Sets and Collations
DiRECTION (0)
REWRITE (2)
'========================================================================'
'
' FROM: AnthonyWJones, see post '
'
'========================================================================'
Dim db: db = "C:\Docs\baywotch.db5"
Dim exportDir: exportDir = "C:\Docs\" '" SO prettify does not do VB well
Dim exportFile: exportFile=NewFileName(exportDir)
Dim cn: Set cn = CreateObject("ADODB.Connection")
cn.Open _
"Provider = Microsoft.Jet.OLEDB.4.0; " & _
"Data Source =" & db
cn.Execute "SELECT * INTO [text;HDR=Yes;Database=" & exportDir & _
";CharacterSet=65001]." & exportFile & " FROM tblAuction"
'Export file
'========================================================================'
'Support functions
Function NewFileName(ExportPath)
Dim fs
Dim NewFileTemp
Set fs = CreateObject("Scripting.FileSystemObject")
NewFileTemp = "CSV" & Year(Date) _
& Right("00" & Month(Date),2) & Right("00" & Day(Date) ,2) & ".csv"
a = fs.FileExists(ExportPath & NewFileTemp)
i = 1
Do While a
NewFileTemp = "CSV" & Year(Date) _
& Right("00" & Month(Date),2) & Right("00" & Day(Date) ,2) & "_" & i & ".csv"
a = fs.FileExists(ExportPath & NewFileTemp)
i = i + 1
If i > 9 Then
'Nine seems enough times per day to be
'exporting a table
a = True
MsgBox "Too many attempts"
WScript.Quit
End If
Loop
NewFileName = NewFileTemp
End Function
Perhaps the easiest way is to use [text...].filename approach:-
Dim db: db = "C:\Docs\LTD.mdb"
Dim exportDir: exportDir = "C:\Docs\" '" SO prettify does not do VB well
Dim exportFile: exportFile = "Exp.txt"
Dim cn: Set cn = CreateObject("ADODB.Connection")
cn.Open _
"Provider = Microsoft.Jet.OLEDB.4.0; " & _
"Data Source =" & db
cn.Execute "SELECT * INTO [text;HDR=Yes;Database=" & exportDir & _
";CharacterSet=65001]." & exportFile & " FROM tblMembers"
FileSystemObject won't help you since it doesn't do UTF-8. UTF-8 is acheived by specifying CharacterSet=65001 (65001 is the UTF-8 codepage). Note the file generated does not contain a UTF-8 BOM but the schema.ini file created will note that the CharacterSet is UTF-8.
Note this doesn't achieve your append requirements are you sure that makes sense anyway, won't you end up with lots of duplicates?
Edit:
The above is adjusted to include the UTF-8 requirement. You can simply append something like the date to create multiple snapshot files for the table.
I've numbered the lines for reference.
1. db = "C:\Docs\LTD.mdb"
2. TextExportFile = "C:\Docs\Exp.txt"
3. strSQL = "SELECT * FROM tblMembers"
4. Set f = fs.CreateTextFile(TextExportFile, True)
Line 1 - is the current access database file you are working with. this case it's LTD.mdb
Line 2 - is the name of the file that you are going to write/append. It's Exp.txt
Line 3 - is the sql statement that will be used to collect the data.
Line 4 - is the command to open the file to write to.
Change line 2 to the name of file you want.
Change line 3 to the table you want to use. Select * will use all the columns if you want only a couple identify them by name. select col1, col2 ... from mytable. You will want to look into using where clauses also.
Change line 4 from CreateTextFile to OpenTextFile and use ForAppending to append.
MSDN VBA
I'm drawing a blank on formatting the line. One of the ways I use is modify the select statement to include commas. example select col1 & "," & col2 from mytable.
For UTF-8 (I don't have a working example) Try:
utf = new String(a, 0, a.length, UTF-8);
f.WriteLine utf;
UTF-8 VBA
Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adClipString = 2
Const ForWriting = 2
Const ForAppending = 8
Const strDB = "C:\Docs\LTD.mdb"
Const strCSV = "C:\Docs\Exp.csv"
Set objAccessConnection = CreateObject("ADODB.Connection")
objAccessConnection.Open "Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;Data Source=" & strDB
Set objAccessRecordset = CreateObject("ADODB.Recordset")
strAccessQuery = "SELECT * FROM tblMembers"
objAccessRecordset.Open strAccessQuery, objAccessConnection, adOpenStatic, adLockOptimistic
Set objCSV = CreateObject("Scripting.FileSystemObject").OpenTextFile(strCSV, ForAppending, True)
objCSV.Write objAccessRecordset.GetString(adClipString,,",",CRLF)
objCSV.Close
Set objCSV = Nothing
objAccessRecordset.Close
Set objAccessRecordset = Nothing
objAccessConnection.Close
Set objAccessConnection = Nothing