2
有人可以幫助我嗎? 我需要通過系統DSN檢查我的ODBC連接到AS400伺服器,並創建一個系統DSN,如果一個特定的不存在。 我試過Google搜索,一直沒能找到對我有好處的東西。檢查系統DSN並創建系統DSN(如果不存在)(i系列訪問ODBC驅動程序)
順便說一句,我是相當新的編程。任何幫助都感激不盡。 謝謝
有人可以幫助我嗎? 我需要通過系統DSN檢查我的ODBC連接到AS400伺服器,並創建一個系統DSN,如果一個特定的不存在。 我試過Google搜索,一直沒能找到對我有好處的東西。檢查系統DSN並創建系統DSN(如果不存在)(i系列訪問ODBC驅動程序)
順便說一句,我是相當新的編程。任何幫助都感激不盡。 謝謝
經過網上提供的幾個較簡單的例子之後,這是我設法想出來的(它對我來說工作正常)。
using System;
using System.Runtime.InteropServices;
public class ODBC_Manager
{
[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);
private const short ODBC_ADD_DSN = 1;
private const short ODBC_CONFIG_DSN = 2;
private const short ODBC_REMOVE_DSN = 3;
private const short ODBC_ADD_SYS_DSN = 4;
private const short ODBC_CONFIG_SYS_DSN = 5;
private const short ODBC_REMOVE_SYS_DSN = 6;
private const int vbAPINull = 0;
public void CreateDSN(string strDSNName)
{
string strDriver;
string strAttributes;
try
{
string strDSN = "";
string _server = //ip address of the server
string _user = //username
string _pass = //password
string _description = //not required. give a description if you want to
strDriver = "iSeries Access ODBC Driver";
strAttributes = "DSN=" + strDSNName + "\0";
strAttributes += "SYSTEM=" + _server + "\0";
strAttributes += "UID=" + _user + "\0";
strAttributes += "PWD=" + _pass + "\0";
strDSN = strDSN + "System = " + _server + "\n";
strDSN = strDSN + "Description = " + _description + "\n";
if (SQLConfigDataSource((IntPtr)vbAPINull, ODBC_ADD_SYS_DSN, strDriver, strAttributes))
{
Console.WriteLine("DSN was created successfully");
}
else
{
Console.WriteLine("DSN creation failed...");
}
}
catch (Exception ex)
{
if (ex.InnerException != null)
{
Console.WriteLine(ex.InnerException.ToString());
}
else
{
Console.WriteLine(ex.Message.ToString());
}
}
}
public int CheckForDSN(string strDSNName)
{
int iData;
string strRetBuff = "";
iData = SQLGetPrivateProfileString("ODBC Data Sources", strDSNName, "", strRetBuff, 200, "odbc.ini");
return iData;
}
}
...然後從您的應用程序調用方法。
static void Main(string[] args)
{
ODBC_Manager odbc = new ODBC_Manager();
string dsnName = //Name of the DSN connection here
if (odbc.CheckForDSN(dsnName) > 0)
{
Console.WriteLine("\n\nODBC Connection " + dsnName + " already exists on the system");
}
else
{
Console.WriteLine("\n\nODBC Connection " + dsnName + " does not exist on the system");
Console.WriteLine("\n\nPress 'Y' to create the connection?");
string cont = Console.ReadLine();
if (cont == "Y" || cont == "y")
{
odbc.CreateDSN(dsnName);
Environment.Exit(1);
}
else
{
Environment.Exit(1);
}
}
}
[This answer](http://stackoverflow.com/questions/334939/)可能會有所幫助。 – dmc 2012-02-13 14:06:58