Sunday, December 27, 2009

How to create a system DSN

The following code checks if a DSN with the given name exists, if not a new DSN will be created.

Code was written using C# :

//Define the following before starting the code.
[DllImport("ODBCCP32.dll")]
public static extern bool SQLConfigDataSource(
IntPtr parent, int request, string driver, string attributes);
[DllImport("ODBCCP32.dll")]
public static extern int SQLGetPrivateProfileString (string lpszSection, string lpszEntry, string lpszDefault,string @RetBuffer, int cbRetBuffer, string lpszFilename );

//In the button click event call the following method with DSN name as input //value

public void CreateDSN(string strDSNName)
{
string driver;
string attributes;


//************ Createing DSN for Access database ********************//
/*
* driver = "Microsoft Access Driver (*.MDB)" + "\0";
* attributes = "DSN=tstDSN" + "\0" + "Uid=" + "\0" + "pwd=" + "\0" + "DBQ=C:\\Test.mdb" + "\0";
*
*/

try
{
driver = "SQL Server";

//- check for ODBC data source

int iData;
string strRetBuff="";
string strDSN="";
strDSN = "DSN : " + strDSNName + " has been created successfully with following
parameters : \n\n";
iData = SQLGetPrivateProfileString("ODBC Data
Sources",strDSNName,"",strRetBuff,200, "odbc.ini");

if(iData > 0)
{
MessageBox.Show("DSN already exists");
}
else
{
if (MessageBox.Show("DSN not found. Would you like to create one ?","DSN
Creation",MessageBoxButtons.YesNo,MessageBoxIcon.Question) == DialogResult.Yes )
{
attributes = "DSN=" + strDSNName + "\0" + "Server=mysqlserver" + "\0" ;
attributes = attributes + "Description=Test Dev Server" + "\0";
attributes = attributes + "Database=mydatabase" + "\0";

strDSN = strDSN + "Server = mysqlserver\n\n";
strDSN = strDSN + "Description=Test Dev Server \n\n";
strDSN = strDSN + "Database=mydatabase \n\n";


if (SQLConfigDataSource((IntPtr)0,4,driver, attributes) )
{
MessageBox.Show ("DSN was created successfully..");
lblStatus.Text = strDSN;
}
else
{
MessageBox.Show ("DSN Creation Failed...");
lblStatus.Text = "DSN creation failed";
}
}
else
{
lblStatus.Text = "DSN was not created as per user request";
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
finally
{}
}

No comments:

Post a Comment