Click here to Skip to main content
15,897,891 members
Articles / Programming Languages / SQL
Article

Creating and populating MS Access files from other databases, using DTS

Rate me:
Please Sign up or sign in to vote.
3.14/5 (10 votes)
31 May 2006CPOL2 min read 91.5K   540   48   22
An article on creating and populating an automated MS Access file from other databases.

Sample Image

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

VB
Imports System.IO
Imports System.Data.OleDb
Module Module1
    Sub Main()
        Try
            'Access DB File path
            Dim File_Path As String
            File_Path = _
             AppDomain.CurrentDomain.BaseDirectory & "db.mdb"
            'If Exists already then delete it first
            If File.Exists(File_Path) Then
                File.Delete(File_Path)
            End If
            'Connection String for New DB File
            Dim Access_ConnStr As String = _
              "Provider=Microsoft.Jet.OLEDB.4.0;" & _ 
              " Data Source=" & File_Path
            'ADOX.Catalog Object to craete new DB
            Dim Catalog As New ADOX.Catalog()
            Catalog.Create(Access_ConnStr)
            Catalog.ActiveConnection.close()
            Catalog = Nothing
            'OleDb Connection to Create New table
            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()
            'Set and Open Connection of the Source DB
            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)
            'Read from Source and populate in the Access DB
            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!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Program Manager ZonG, China Mobile Company
Pakistan Pakistan
I am working as Manager Enterprise Services where key responsibilities are to support end users on their day to day IT related issues.
The other function I am responsible is IT IPCC Services Support Since September 2013 and my key responsibilities are to maintain IPCC Uptime along with end users support at both CMPak call centers. IPCC enhancements and new feature development is also part of my job role.
The third area that was handed over to me in March 2015 is in-house apps support, where key responsibility is to provide support for all the application developed by IT department and to maintain the availability of these applications.
Previously I was working as Manager Automation & Planning and this is my key area of expertise. My responsibilities were to manage team in Project Planning, System Analysis, Requirements gathering, Preparation of SRS, Presentations to client about the requirements, getting Approvals on SRS from the Client, Database Design, Development Tracking, System Deployments, end user Feedback along with Change Management.

Planning and Defining Scope, Resource Planning, Time Estimating, Creating Charts and Schedules, Risk Analysis
Managing Risks and Issues, Monitoring and Reporting Progress, Team Leadership, Working with Vendors, Scalability were the key area of working along with an efficient problem-solver in professional way with envisions business and technical perspectives to develop workable solutions.

I started my career as developer in 2004 and promoted as team lead IT Automation in 2007 and then as manager so I spend 7 years in Software Development & Project Planning.

Comments and Discussions

 
GeneralUsing log files to update an Access database Pin
Cher122127-Sep-10 9:31
Cher122127-Sep-10 9:31 
GeneralAdding another Table Pin
MGDude11-Jun-08 19:03
MGDude11-Jun-08 19:03 
Questiondts ? Pin
scalpa981-Nov-07 10:04
scalpa981-Nov-07 10:04 
Generalcsv file Pin
scalpa9831-Oct-07 8:21
scalpa9831-Oct-07 8:21 
GeneralRe: csv file Pin
Malik Nasir1-Nov-07 3:08
Malik Nasir1-Nov-07 3:08 
Questionupdate DATE datatype into access Pin
Questionaire24-Nov-06 17:01
Questionaire24-Nov-06 17:01 
AnswerRe: update DATE datatype into access Pin
Malik Nasir26-Nov-06 19:17
Malik Nasir26-Nov-06 19:17 
QuestionWhat's the fastest way to populate an MS Access table? Pin
MelStalcup28-Jun-06 10:12
MelStalcup28-Jun-06 10:12 
GeneralCopying a table from one Access db to another Pin
dralexh9-Jun-06 2:18
dralexh9-Jun-06 2:18 
GeneralRe: Copying a table from one Access db to another Pin
James H11-Jun-06 23:14
James H11-Jun-06 23:14 
GeneralRe: Copying a table from one Access db to another Pin
Malik Nasir12-Jun-06 0:19
Malik Nasir12-Jun-06 0:19 
GeneralRe: Copying a table from one Access db to another Pin
dralexh12-Jun-06 2:21
dralexh12-Jun-06 2:21 
GeneralRe: Copying a table from one Access db to another Pin
Malik Nasir12-Jun-06 21:41
Malik Nasir12-Jun-06 21:41 
QuestionDTS? Pin
michaelschuer5-Jun-06 23:34
michaelschuer5-Jun-06 23:34 
AnswerRe: DTS? Pin
Malik Nasir6-Jun-06 0:41
Malik Nasir6-Jun-06 0:41 
AnswerRe: DTS? Pin
vlad.pitaru6-Jun-06 5:36
vlad.pitaru6-Jun-06 5:36 
GeneralRe: DTS? Pin
Malik Nasir8-Jun-06 18:51
Malik Nasir8-Jun-06 18:51 
GeneralRe: DTS? Pin
Ziener16-Nov-06 22:48
Ziener16-Nov-06 22:48 
GeneralRe: DTS? Pin
Lutosław10-Jan-12 0:11
Lutosław10-Jan-12 0:11 
QuestionHi, Pin
| Muhammad Waqas Butt |2-Jun-06 23:06
professional| Muhammad Waqas Butt |2-Jun-06 23:06 
AnswerRe: Hi, Pin
Malik Nasir4-Jun-06 19:34
Malik Nasir4-Jun-06 19:34 
AnswerRe: Hi, Pin
James H11-Jun-06 23:23
James H11-Jun-06 23:23 
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)

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.