Learning never exhausts the mind

By

This short snippet can be used to add ODBC system DSN data source on the fly without having to enter Windows Control Panel to configure manually.

This snippet creates a wrapper function to the Microsoft ODBC interface to add ODBC System DSN. You can extend this to include other database drivers in addition to MS Access 2000.

ODBC stands for Open Database Connectivity and is the standard programming language API for accessing database management systems.

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            bool success = Utils.CreateDataSource(Utils.ODBC_Drivers.Access2000, "MyDataSource", "c:database.mdb");
            if (success)
            {
                Console.WriteLine("DataSource Created OK");
            }
            else
            {
                Console.WriteLine("There was a problem creating DataSource");
            }
            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }

        public static class Utils
        {
            [DllImport("ODBCCP32.dll")]
            private static extern bool SQLConfigDataSource(IntPtr hwndParent, int fRequest, string lpszDriver, string lpszAttributes);

            // Add odbc system DSN
            public static bool CreateDataSource(string ODBCDriver, string DataSourceName, string DatabasePath)
            {
                return SQLConfigDataSource((IntPtr)0, ODBC_Request_Modes.ODBC_ADD_DSN, ODBCDriver, "DSN=" + DataSourceName + "Uid=Adminpwd=DBQ=" + DatabasePath + "");
            }

            // Request modes
            public static class ODBC_Request_Modes
            {
                public static int ODBC_ADD_DSN = 1;
                public static int ODBC_CONFIG_DSN = 2;
                public static int ODBC_REMOVE_DSN = 3;
                public static int ODBC_ADD_SYS_DSN = 4;
                public static int ODBC_CONFIG_SYS_DSN = 5;
                public static int ODBC_REMOVE_SYS_DSN = 6;
            }

            // List of ODBC Driver types
            public static class ODBC_Drivers
            {
                public static string Access2000 = "Microsoft Access Driver (*.MDB)";
            }
        }
    }
}

 

Did you enjoy this post? Let others know!

If you enjoyed this post, please share it with others. Click one of the social media buttons below to share on Facebook, Twitter, LinkedIn, Pinterest or email to a friend.

Leave a Reply

Fields marked with * are mandatory.

We respect your privacy, and will not make your email public. Hashed email address may be checked against Gravatar service to retrieve avatars. This site uses Akismet to reduce spam. Learn how your comment data is processed.