How To Programmatically Create A DSN For SQL Server With VB
How To Programmatically Create A DSN For SQL Server With VB
with VB
DSNs are usually created through the ODBC Data Source Administrator window, which is
accessible from the Windows Control Panel (or Administrator Tools in Windows 2000). Other
techniques that provide access to ODBC-compliant databases include using RegisterDatabase (a
Data Access Object (DAO) method), using the SQLConfigDataSource ODBC API function, or
using a DSN-less connection string.
However, it is possible to establish a new DSN by manually creating and manipulating values in
the Windows Registry. The following technique uses the RegCreateKey, RegSetValueEx, and
RegCloseKey API functions to create a system DSN for a SQL Server database.
Step-by-Step Procedures
1. Open a new Visual Basic project. Form1 is created by default. Put a CommandButton on
Form1 (Command1), and put the following code in the General Declarations section of
the code for Form1:
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
Option Explicit
Private Const REG_SZ = 1
'Constant for a string variable type.
Private Const HKEY_LOCAL_MACHINE = &H80000002
Private Declare Function RegCreateKey Lib "advapi32.dll" Alias _
"RegCreateKeyA" (ByVal hKey As Long, ByVal lpSubKey As String, _
phkResult As Long) As Long
18. Place the following code in the click event of the Command1 button on Form1:
Change the values of the DataSourceName, DatabaseName, Description, DriverPath,
LastUser, and Server variables as appropriate for your environment. Any of the drivers
listed on the ODBC Drivers tab of the ODBC Data Source Administrator window can be
used as part of the DriverPath variable. All of these drivers can be found in
DataSourceName As String
DatabaseName As String
Description As String
DriverPath As String
DriverName As String
LastUser As String
Regional As String
Server As String
69.
70.
71.
72.
73.
74.
75.
lResult = RegCreateKey(HKEY_LOCAL_MACHINE, _
"SOFTWARE\ODBC\ODBC.INI\ODBC Data Sources", hKeyHandle)
lResult = RegSetValueEx(hKeyHandle, DataSourceName, 0&, REG_SZ, _
ByVal DriverName, Len(DriverName))
lResult = RegCloseKey(hKeyHandle)
End Sub
76. Run the project and click on the Command1 command button. Then open up the ODBC
Data Source Administrator from the Control Panel (or Administrator Tools in Windows
2000). Your new DSN will appear along with the other system DSNs that you have
already created.
Step-by-Step Example
1. Start a New Project.
2. In the Advanced tab of the Options dialog box under the Tools menu, set a Conditional
Compilation Argument named WIN32 equal to 1 if using Visual Basic 4.0 32-bit, or 0 if
using Visual Basic 4.0 16-bit.
3. Add two CommandButtons to the default form.
4. Add the following code to the General Declarations:
5.
6.
7.
8.
9.
Option Explicit
'Constant Declaration
Private Const ODBC_ADD_DSN = 1
Private Const ODBC_CONFIG_DSN = 2
source
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
As Long
#Else
Private Declare Function SQLConfigDataSource Lib
"ODBCINST.DLL" _
22.
(ByVal hwndParent As Integer, ByVal fRequest As Integer,
ByVal _
23.
lpszDriver As String, ByVal lpszAttributes As String) As
Integer
24.
#End If
25. Add the following code into the Click event of Command1:
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51. Add the following code into the Click event of Command2:
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
NOTE: The driver name must be surrounded by curly brackets. For example:
"{SQL Server}"
The following information is taken from Visual Basic Books Online:
The connect string contains a series of semi-colon-delimited arguments as defined by the ODBC
interface - including the ODBC driver itself. That is, all ODBC drivers have specific argument
requirements so you should consult the documentation included with the driver for specific
information. This connect string is passed to the ODBC API SQLDriverConnect function along
with the hEnv for the associated rdoEnvironment object.
If you do want to set up a DSN, you can use the following methods:
Sample Program
The following RDO example uses a "DSN-less" ODBC connection so you do not need to set up
a DSN with the ODBC Admin utility beforehand.
1. Start a new project in Visual Basic. Form1 is created by default.
2. Add a CommandButton to Form1, Command1 by default.
3. Paste the following code into the code window of Form1.
Note You must change UID =<username> and PWD =<strong password> to the correct
values before you run this code. Make sure that UID has the appropriate permissions to
perform this operation on the database.
4.
5.
'creatable rdoConnection
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
'creatable rdoQuery
'pointer to rdoResultset
'hold connection info
23. Note that you must change your DRIVER, SERVER, DATABASE, UID, and PWD
parameters in the Connect method. You also need to modify the SQL statement contained
in the Command1_Click event to match your own SQL data source.
24. Start the program or press the F5 key.
25. Click the Command1 button to create an rdoResultset and display the first row of data in
the debug window.
"database=mydb;Username=<username>;PWD=<strong password>;dsn=;"
Set cn = en.OpenConnection("", False, False, cnstr)
NOTE: The driver name must be surrounded by curly brackets. For example: "{SQL Server}."
(CAUTION: DSN-Less connections will not work in Visual Basic 4.0 16-bit. If you try to use
them you will get a General Protection Fault in module ODBC.DLL at 0006:080F.)
In Microsoft Visual Basic version 3.0 for Windows, you had to create a DSN that added an extra
step when distributing your application because each workstation had to have the DSN created in
order to access the specified server and database. This was done either manually with the ODBC
Admin utility, through code with the RegisterDatabase function, or through code with the
SQLConfigDatasource API function. For additional information on how to do this setup
manually, please see the following articles in the Microsoft Knowledge Base:
123008 TITLE : How to Set Up ODBC Data Sources When Distributing an App
126940 : RegisterDatabase Fails After ODBC Version 2.x Installed
132329 : RegisterDatabase Method Does Not Modify ODBC.INI File
Sample Program
The following RDO example uses a "DSN-less" ODBC connection so you do not need to set up
a DSN with the ODBC Admin utility beforehand.
1. Start a new project in Visual Basic. Form1 is created by default.
2. Add a command button to Form1, Command1 by default.
3. Paste the following code into the General Declarations section of Form1.
Note You must change Username= <username> and PWD =<strong password> to the
correct values before you run this code. Make sure that Username has the appropriate
permissions to perform this operation on the database.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
Dim en As rdoEnvironment
Dim cn As rdoConnection
Private Sub Form_Load()
MousePointer = vbHourglass
Dim strConnect As String
' Change the next line to reflect your driver and server.
strConnect = "driver={SQL Server};server=jonfo5;" & _
"database=pubs;Username=<username>;PWD=<strong password>;"
Set en = rdoEngine.rdoEnvironments(0)
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
Set cn = en.OpenConnection( _
dsName:="", _
Prompt:=rdDriverNoPrompt, _
ReadOnly:=False, _
Connect:=strConnect)
cn.QueryTimeout = 600
MousePointer = vbNormal
End Sub
Private Sub Command1_Click()
MousePointer = vbHourglass
Dim rs As rdoResultset
Set rs = cn.OpenResultset(Name:="Select * from authors", _
Type:=rdOpenForwardOnly, _
LockType:=rdConcurReadOnly, _
Options:=rdExecDirect)
Debug.Print rs(0), rs(1), rs(2)
MousePointer = vbNormal
End Sub
33. Note that you must change your DRIVER, SERVER, DATABASE, UID, and PWD
parameters in the OpenConnection method. You also need to modify the SQL statement
contained in the Command1_Click event to match your own SQL data source.
34. Check the Microsoft Remote Data Object in the Project References.
35. Start the program or press the F5 key.
36. Click the Command1 button to create a rdoResultset and display the first row of data in
the debug window.
ODBC Setup
RegisterDatabase
ODBC API
MORE INFORMATION
Required Files
The following files must be distributed with your application if you use ODBC. When
using the Setup Wizard to create distribution disks, ensure that the necessary files
are included in the file list. All of the files listed should be installed in the
\WINDOWS\SYSTEM directory.
Optional files (SQL Server or Oracle) are denoted with an asterisk (*).
File
Description
---------------------------------------------------------------------ODBC.DLL
The ODBC Driver Manager. This DLL is called by the
Microsoft Jet database engine when performing ODBC
operations. The Driver Manager handles loading the
correct ODBC driver and dispatching ODBC function
calls to the driver.
ODBCINST.DLL
ODBCADM.EXE
ODBCINST.HLP
COMMDLG.DLL
CTL3D.DLL
PDSODBC.DLL
<driver>.DLL
SQLSRVR.DLL*
Oracle 6:
<netlib>.DLL
SQORA.DLL*
INSTCAT.SQL*
DRVSSRVR.HLP*
ORASETUP.DLL*
DRVORACL.HLP*
ORACLE.TXT*
ODBC.INI
ODBCINST.INI
The .INI files store information about the ODBC driver(s) and the ODBC Data
Sources. As a result, they are variable -- a user's may already have them installed in
the \WINDOWS directory. If a developer were to blindly copy ODBC.INI and
ODBCINST.INI onto the user's computer, the new files may overwrite existing Data
Sources.
Below are four methods you can use to get DSN information into the user's
ODBC.INI and ODBCINST.INI files.
ODBC Setup
To install an ODBC Driver and establish an ODBC Data Source, the Visual Basic
online Help documentation recommends that you copy the entire contents of the
\VB\ODBC directory to an additional distribution disk.
As a developer, you can specify that the disk be inserted and SETUP.EXE run from
the floppy disk. In addition, you can prompt the user to insert the ODBC floppy disk,
and then use the Visual Basic Shell command to shell out to SETUP.EXE.
The Setup Wizard copies and modifies SETUP1.MAK into SETUP1A.MAK during the
process of creating distribution disks. It builds SETUP1A.MAK into SETUP1.EXE,
compresses it, and copies it to the distribution disks. When SETUP.EXE is executed
on the distribution disks, the files in SETUP.LST are copied to the destination
computer. SETUP1.EX_ is then uncompressed and executed to start copying files
from the floppy disks to the destination computer.
It is possible to then modify SETUP1A.MAK, rebuild SETUP1.EXE, compress it, and
copy it to the distribution disks. To ensure that the compressed file size will fit on
the first distribution disk, you must pad the project with code prior to first executing
the Setup Wizard. Then you can change the code into comments and add new code
to prompt for the ODBC Setup disk. The resulting EXE size will then still fit on the
first distribution floppy disk.
Modify SETUP1.FRM in the \VB\SETUPKIT\SETUP1 directory to add the necessary
code to pad the executable. This file is copied into SETUP1A.MAK during the Setup
Wizard's execution.
NOTE: Microsoft Technical Support does not support the modification of the Setup
process or any of the setup files. Support is provided for the Setup Wizard and the
files it creates on an "as is" basis only.
Here are the steps to follow:
1. Start Visual Basic and from the File menu, choose Open Project. Open
SETUP1.MAK in the \VB\SETUPKIT\SETUP directory.
2. Select SETUP1.FRM from the project window. Press F7 to view the code.
3. At the end of the Form_Load procedure add the following code in the ExitSub:
label part, after RestoreProgMan and before the End statement:
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
tmpS
tmpS
tmpS
tmpS
tmpS
tmpS
tmpS
tmpS
tmpS
tmpS
tmpS
tmpS
tmpS
tmpS
tmpS
Next I
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
Mid$(tmpK,
Mid$(tmpK,
Mid$(tmpK,
Mid$(tmpK,
Mid$(tmpK,
Mid$(tmpK,
Mid$(tmpK,
Mid$(tmpK,
Mid$(tmpK,
Mid$(tmpK,
Mid$(tmpK,
Mid$(tmpK,
Mid$(tmpK,
Mid$(tmpK,
Mid$(tmpK,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
2)
2)
2)
2)
2)
2)
2)
2)
2)
2)
2)
2)
2)
2)
2)
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
2)
2)
2)
2)
2)
2)
2)
2)
2)
2)
2)
2)
2)
2)
24.
25.
26.
27.
28.
29.
'
'
'
'
'
'
'Next
tmpS
tmpS
tmpS
tmpS
tmpS
tmpS
I
=
=
=
=
=
=
Mid$(tmpK,
Mid$(tmpK,
Mid$(tmpK,
Mid$(tmpK,
Mid$(tmpK,
Mid$(tmpK,
1,
1,
1,
1,
1,
1,
2)
2)
2)
2)
2)
2)
30.Add the following code within the Form_Load procedure immediately following
the commented code:
31.
32.
33.
34.
35.
36.
37.
38.Change the disk number to 1 greater than the total number of distribution
disks created. The disk number is the first parameter to the
PromptForNextDisk procedure. In this example, the next disk to prompt for is
2.
39.Save the SETUP1A.MAK project and create the executable as SETUP1.EXE in
the \VB\SETUPKIT\SETUP1 directory (ALT, F, K).
40.Shell out to an MS-DOS command prompt and change the directory to
\VB\SETUPKIT\SETUP1. Execute the following at the command prompt:
\VB\SETUPKIT\KITFILES\COMPRESS -r SETUP1.EXE
41.Place the first distribution floppy disk in the appropriate drive and copy
SETUP1.EX_ to the floppy disk:
copy SETUP1.EX_ A:\SETUP1.EX_
Now, when your distribution disks are run, the final step will be to prompt for the
ODBC Setup and Installation disk. SETUP.EXE will be executed from this disk and the
user can then install the appropriate ODBC driver and create the necessary Data
Source. You should include instructions for this process.
For more information on modifying SETUP1.EXE please refer to Chapter 25,
"Distributing Your Application" in the Microsoft Visual Basic Programmer's Guide.
RegisterDatabase
Visual Basic provides the RegisterDatabase statement to help in installing ODBC
data sources, not drivers. The RegisterDatabase statement assumes that
ODBCINST.INI and ODBCINST.DLL already exist on the computer. That is, the drivers
must be installed before running RegisterDatabase. If so, the developer can use
RegisterDatabase to add or update an entry in the ODBC.INI.
The problem with this method is that if the client computer does not have ODBC
installed on the computer, the ODBCINST.INI and DLL will not exist. Also, if the ODBC
driver is new to the computer, there will not be an entry for it in ODBCINST.INI, so
RegisterDatabase will fail then as well.
The following description, syntax, remarks, and example about the
RegisterDatabase statement come from the Visual Basic online Help:
Description:
Makes connect information for an ODBC data source name available for use by the
OpenDatabase function.
Syntax:
RegisterDatabase dsn, driver, silent, attributes
Remarks: The RegisterDatabase statement has the following parts:
DRIVER: A string expression that is the name of the ODBC driver. This is not
the name of the ODBC driver DLL file. For example, "SQL Server" or "Oracle"
are driver name but "SQLSRVR.DLL" is the name of a DLL file. You must have
ODBC and the appropriate driver already installed.
SILENT: A numeric expression that is True if you do not want to display the
ODBC driver dialogs that prompt for driver-specific information, or False if you
do want to display the ODBC driver dialogs. If silent is True, then attributes
must contain all the necessary driver-specific information or the dialog will
appear anyway.
Example:
Sub Command1_Click ()
Dim att As String
Dim mydb As Database
att = "Description = SQL Server on server Texas" & Chr$(13)
att
att
att
att
att
att
=
=
=
=
=
=
att
att
att
att
att
att
&
&
&
&
&
&
If the database is already registered in the ODBC.INI file, the entry is updated. If
RegisterDatabase fails for any reason, no changes are made to the ODBC.INI file and
an error occurs.
ODBC API
This is probably the most flexible and most efficient method, but most developers
are not familiar with it and do not have the ODBC SDK that documents the API.
Developers should get the Microsoft Software Development Kit (SDK) and get the
"Microsoft ODBC 2.0 Programmer's Reference and SDK Guide" from Microsoft Press.
Copy INI
If the developer is certain that an ODBC.INI and ODBCINST.INI do not exist on the
installation computer, they can simply copy the files. However, the developer must
ensure that the paths to the drivers are correct; paths are fully qualified within the
.INI files. For example, the ODBC.INI file will specify
C:\WINDOWS\SYSTEM\SQLSRVR.DLL as the driver for SQL Server, so if the user's
Windows setup is in \WIN31, the path won't work.