Web Design that taps into the haromny and vision of your dreams.

Using C# to Add an ODBC System DSN

By on in Coding

248 words, estimated reading time 2 minutes.

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)";
            }
        }
    }
}
 

Last updated on: Wednesday 21st June 2017

 

Comments

Have a question or suggestion? Please leave a comment to start the discussion.

 

Leave a Reply

Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

Your email address will not be published.