|

Introduction
If you are using databases like Oracle or SQL Server and you want to copy data from them to some other database that is not linked to your data in any way, you can do this by using some DTS like SQL Server, but the exact scenario that compelled me to develop this utility was to “do all in an automated way”. I developed this application to convert my source data to MS Access file format but the same can be used to convert any kind of data source to MS Access.
Background
As I mentioned earlier, the reason to develop this application was to do everything in an automated way. That means, I want to periodically convert my source data to MS Access in an automated fashion.
Code
Imports System.IO
Imports System.Data.OleDb
Module Module1
Sub Main()
Try
Dim File_Path As String
File_Path = _
AppDomain.CurrentDomain.BaseDirectory & "db.mdb"
If File.Exists(File_Path) Then
File.Delete(File_Path)
End If
Dim Access_ConnStr As String = _
"Provider=Microsoft.Jet.OLEDB.4.0;" & _
" Data Source=" & File_Path
Dim Catalog As New ADOX.Catalog()
Catalog.Create(Access_ConnStr)
Catalog.ActiveConnection.close()
Catalog = Nothing
Dim Access_Conn As OleDb.OleDbConnection
Access_Conn = New OleDb.OleDbConnection(Access_ConnStr)
Access_Conn.Open()
Dim strSQL As String = "CREATE TABLE tblTest (" & _
" TerritoryID Text(20)," & _
" TerritoryDescription Text(50)," & _
" RegionID Number);"
Dim cmd As OleDbCommand = Access_Conn.CreateCommand()
cmd.CommandText = strSQL
cmd.ExecuteNonQuery()
Dim SrcConnStr As String = "Provider=sqloledb; " & _
"Data Source=(local); Initial Catalog=northwind; " & _
"User Id=sa; Password=;integrated " & _
"security=SSPI;persist security info=False;"
Dim SrcConn As New OleDbConnection(SrcConnStr)
SrcConn.Open()
Dim srcReader As System.Data.OleDb.OleDbDataReader
strSQL = "select * from Territories"
Dim SrcCmd As New OleDbCommand(strSQL, SrcConn)
srcReader = SrcCmd.ExecuteReader()
While srcReader.Read
strSQL = "insert into tblTest values('" & _
srcReader.GetValue(0).ToString & "','" _
& srcReader.GetValue(1).ToString & _
"','" & srcReader.GetValue(2).ToString & "')"
cmd.CommandText = strSQL
cmd.ExecuteNonQuery()
End While
cmd.Dispose()
cmd = Nothing
Access_Conn.Close()
Access_Conn.Dispose()
Access_Conn.ReleaseObjectPool()
Access_Conn = Nothing
srcReader.Close()
srcReader = Nothing
SrcCmd.Dispose()
SrcCmd = Nothing
SrcConn.Close()
SrcConn.Dispose()
SrcConn = Nothing
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Module
Working with the demo
Download the demo project and unzip it, and then run "DTS.exe". It will generate an MS Access file “db.mdb” in the same directory. If you view this file, it will contain all the data of the Northwind database of SQL Server. Note: To run this demo application, SQL Server must be installed on your machine.
Working with the code
Download the code and open it in Visual Studio .NET, then do the following changes if you want to change this according to your requirement:
- Change “
File_Path” and set it where you want to create a new file.
- Change the
Create Table command at line 26 according to your source table.
- If you are using databases other than SQL Server then change the connection string for your source DB, at line 36.
- Change the source ‘
Select’ command at line 41.
- Change the ‘
Insert’ command at line 47 according to the source and destination tables.
That’s al...
Points of Interest
- The application can be designed to import multiple tables.
- The console application can be scheduled as an automated data import utility.
- The application can be designed in such a way that the user just has to select a database and click to import the data.
Summary
There are so many tools for DTS, but this is an effort to do the same in my own desired way; and using this single application, many targets can be achieved. So use this in your own way. Happy programming!
| You must Sign In to use this message board. |
|
| | Msgs 1 to 20 of 20 (Total in Forum: 20) (Refresh) | FirstPrevNext |
|
 |
|
|
Hey guys, i understand how to modify the module to create 1 table in access from a table of view in sql server, but i am having trouble with exporting 2 tables into access from Sql server, so if anyone could help me that would be great
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
thanks for your quick response. I seek everywhere in sql server express 2005 for dts. But no idea where it is !!! Perhaps it exists only in real sql sever not in express version? Arrgh !
scalpa http://www.scalpa.info
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
hello from a newbies of normandy Is it possible to use your code to import data from some columns (not all) of a csv file ? And fill an existing Access table with it ? thanks for your help pascal
scalpa http://www.scalpa.info
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
use DTS import/Export utility of SQL Server for this and save the project in vb, you will get the comeplete code for this then you can check occrdingly.
regards
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
I'm coding simple database program by using VB and MS access database. How can I use update statment in order to update DATE datatype into access database?
P.S. For inserting statement, I code  "Insert into price (cus_id, prod_id, flag, [date], price) values (cus_value, prod_value, flag_value, date_value, price_value)"
This data record can be inserted successfully. (date_value is STRING data type)
For update statement, I code "Update price set ([date] = date_value ) where (cus_id = cus_value)" This data record cannot be updated into price table
I'm so confuse why it doesn't work since I use the same syntax by using [].
Actually, I have alredy tried to use another syntax by changing date field into "Update price set (date = #date_value#) where (cus_id = cus_value)" It's also doesn't work.
Please help me to find out the solution.
Thanks in advance
Please help Questionaire
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
this query Update price set (date = #date_value#) will never work. there are two different solutions plz try these
1. try this query Update price set [date] = #date_value#
2. Change the name of the field "date" as this is reserved word so plz change it with some other word as trans_date or some thing like this.
regards
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Hi,
Can anyone tell me what is the fastest way to populate an MS Access table? INSERT statements? Importing from a file?
If importing from a file, how can I accomplish this programmatically?
Thanks!
|
| Sign In·View Thread·PermaLink | 1.00/5 (1 vote) |
|
|
|
 |
|
|
I wonder if I might ask the following question, as I searched through the articles and this article was the closest to what I'd like to do. I want to copy a table from one Access database to another Access database, preserving field names, lengths, the primary key, etc. I am a hobbyist programmer and this task is beyond my skills.
Dralexh
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Open both Access databases in two different instances of MS Access - go to tables view right click and choose "Copy" in source and then go to tables view right click in white space and choose "Paste" in destination - you then get a choice if you want to paste just the structure or the structure and data
|
| Sign In·View Thread·PermaLink | 1.00/5 (1 vote) |
|
|
|
 |
|
|
 |
|
|
Hmmm, yes, and thanks for the response. But how is it easiest for a hobbyist programmer to do it *programmatically*?
Dralexh
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
You can do this in two ways 1. Using the same application ie this article, replace SQL Server with Access and generate an access file that means ur source and destination DB will be MS access 2. Using the following code Dim dbe, dbe1 As Object Dim db, db1 As Object Dim tdf As Object Dim fld As Object Dim prp As Object Dim rs, rs1 As Object
dbe = New DAO.DBEngine() db = dbe.CreateDatabase("c:\test.mdb", _ ";LANGID=0x0409;CP=1252;COUNTRY=0") tdf = db.CreateTableDef("Table1") fld = tdf.CreateField("Field1", 10, 255) tdf.Fields.Append(fld) db.TableDefs.Append(tdf) rs = db.OpenRecordset("Table1")
dbe1 = New DAO.DBEngine() db1 = dbe.OpenDatabase("c:\test1.mdb") rs1 = db1.OpenRecordset("Table1") While Not rs1.eof rs.AddNew() rs!Field1 = rs1!Field1 rs.Update() rs1.movenext() End While
rs.Close() rs = Nothing db.Close() db = Nothing dbe = Nothing
rs1.Close() rs1 = Nothing db1.Close() db1 = Nothing dbe1 = Nothing
i have idea what is ur issue you want to directly copy all the tables and data from one file to other i donot know any such mechanisam i think u always need to create table first then populate it. anyways try this
Regards
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Actually this code does NOT use DTS ... does it make a difference? Yes it does! Performance is the difference. I need to export a table containing close to 1 mil. Rows from SQL Server to access ... in this context I just cannot work without real DTS.
Still ... if someone managed to convert the vb6 code generated by SQL Server successfully to .NET ... I would be really intrested
|
| Sign In·View Thread·PermaLink | 1.50/5 (2 votes) |
|
|
|
 |
|
|
I use the same code to export table containing more than 1 mil rows. I know this is time taking and there are some other issue too but u can say i have no other option but me still working on it so can u please provide me the code i will try to convert that one
Regards
|
| Sign In·View Thread·PermaLink | 1.00/5 (1 vote) |
|
|
|
 |
|
|
 |
|
|
Yeh i agree but the reason is the heading of the article was "Creating and populating MS Access files from other databases like DTS" but the auditors change the heading and now i donot know how to change it
Regards
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Best way to save the table, is to save it in an XML file. use the recorset.save method. XML files can be created on a fly.
Maktub !! Its written
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Nice artical can you please tell how can i export/import all tables data from SQL Server 2000 to MS Access?
Can we export data from SQL Server 2000 to MS Access through SQL Script file?
Thanks and Regards,
|Muhamad Waqas Butt| waqasb4all@yahoo.com www.sktech.freewebspace.com
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
use the following query for sql server, this will return aal the table name so use them in a loop to import all the tables.
select table_name from information_schema.tables where table_Type='BASE TABLE'
regards
|
| Sign In·View Thread·PermaLink | 3.00/5 (1 vote) |
|
|
|
 |
|
|
Yes - below is a sample of script to do this - this is for a specific task and requires an "Empty" Access database with proper table definitions in it as the "template" for the copy. Also this script only takes tables with a particular prefix and can change that prefix in the Access dest - basically it uses SQL Servers ability to link direct to Access db
CREATE PROCEDURE WCLVecUtil_CopySQLFlowToAccess ( @SQLFlowPrefix varchar(20) = 'FLOW_', @AccessFlowPrefix varchar(20) = 'VEC_', @EmptyAccessFlow varchar(255) = NULL, @FlowArcDir varchar(255) = NULL ) AS DECLARE @SQLTableLike varchar(30) DECLARE @Ret int DECLARE @cmdstring varchar(500) DECLARE @DateStamp varchar(30) DECLARE @AccessFile varchar(500) DECLARE @LinkedAccess varchar(500) DECLARE @SQLString NVARCHAR(4000) DECLARE @SourceTable varchar(100) DECLARE @LastTable varchar(100) DECLARE @Col varchar(100) DECLARE @DestTable varchar(100) DECLARE @ColList varchar(8000)
/* First check we have the parms we really need explicitly */
IF @EmptyAccessFlow Is NULL BEGIN PRINT 'You must specify a path to an empty MS Access Flow Database to copy to in parameter @EmptyAccessFlow' RETURN(-1) END IF @FlowArcDir Is NULL BEGIN PRINT 'You must specify a path to directory to save the MS Access copy of the flow to in parameter @FlowArcDir' RETURN(-2) END
/* Make a copy of the base database */ SET @DateStamp = replace(replace(replace(convert(varchar,getdate(),120),'-',''),':',''),' ','_') SET @AccessFile = @FlowArcDir + @DateStamp + '_FLOW.MDB' SET @LinkedAccess = 'FLOW_' + @DateStamp SET @cmdstring = 'COPY ' + @EmptyAccessFlow + ' ' + @AccessFile EXEC @Ret = master..xp_cmdshell @cmdstring IF (@Ret <> 0) BEGIN PRINT 'Failed to make a copy of the empty Access flow database (' + @cmdstring + ')' RETURN(-3) END ELSE BEGIN /* We have an empty copy of the Access flow database to work with - now make it a linked server */ EXEC sp_addlinkedserver @LinkedAccess, 'WCL Flow Copy', 'Microsoft.Jet.OLEDB.4.0', @AccessFile /* And map logins - make it the same for all SQL logins */ EXEC sp_addlinkedsrvlogin @LinkedAccess, false, NULL, 'Admin', NULL /* Set pattern match for the tables we are going to look for to copy */ SET @SQLTableLike = Replace(@SQLFlowPrefix,'_','[_]') + '%'
/* Now we need to go through all the tables in our SQL flow and copy to Access */ SET @LastTable = '' DECLARE tcol_cursor CURSOR FOR SELECT c.TABLE_NAME,'[' + c.COLUMN_NAME + ']' COLNAME FROM INFORMATION_SCHEMA.COLUMNS c INNER JOIN INFORMATION_SCHEMA.TABLES t ON c.TABLE_CATALOG=t.TABLE_CATALOG and c.TABLE_SCHEMA=t.TABLE_SCHEMA and c.TABLE_NAME=t.TABLE_NAME WHERE c.TABLE_NAME LIKE 'FLOW_%' AND t.TABLE_TYPE='BASE TABLE' ORDER BY c.TABLE_NAME,c.ORDINAL_POSITION OPEN tcol_cursor FETCH NEXT FROM tcol_cursor INTO @SourceTable,@Col WHILE (@@FETCH_STATUS <> -1) BEGIN IF (@@FETCH_STATUS <> -2)BEGIN -- PRINT 'Retrieved ' + @SourceTable + ':' + @Col IF @SourceTable<>@LastTable BEGIN /* Moving on to a new table */ IF @LastTable<>'' BEGIN /* Do final copy over of last table's data */ PRINT 'Finishing off previous table ' + @LastTable SET @SQLString = N'INSERT INTO ' + @DestTable + ' (' + @ColList + ') SELECT ' + @ColList + ' FROM ' + @LastTable PRINT ' Copy string is: ' + @SQLString EXEC sp_executesql @SQLString /* Moving on to new table */ END SET @LastTable = @SourceTable PRINT ' ' PRINT 'Starting new table ' + @SourceTable PRINT ' ' SET @ColList = @Col SET @DestTable = @LinkedAccess + '...' + Stuff(@SourceTable,1,Len(@SQLFlowPrefix),@AccessFlowPrefix) SET @SQLString = N'DELETE FROM ' + @DestTable PRINT 'Clearing destination table with: ' + @SQLString EXEC sp_executesql @SQLString END ELSE BEGIN SET @ColList = @ColList + ',' + @Col END END FETCH NEXT FROM tcol_cursor INTO @SourceTable,@Col END
/* Now we need to mop up the last table in list */ IF @LastTable<>'' BEGIN /* Do final copy over of last table's data */ PRINT 'Finishing off last table ' + @LastTable SET @SQLString = N'INSERT INTO ' + @DestTable + ' (' + @ColList + ') SELECT ' + @ColList + ' FROM ' + @LastTable PRINT ' Copy string is: ' + @SQLString EXEC sp_executesql @SQLString END CLOSE tcol_cursor DEALLOCATE tcol_cursor /* Clean up by removing the linked server to the Access database */
EXEC sp_dropserver @LinkedAccess,'droplogins' END RETURN(0)
|
| Sign In·View Thread·PermaLink | 2.67/5 (3 votes) |
|
|
|
 |
|
|
General News Question Answer Joke Rant Admin
|