gpt4 book ai didi

c# - 检查系统 DSN 并创建系统 DSN(如果不存在)(iSeries Access ODBC 驱动程序)

转载 作者:行者123 更新时间:2023-11-30 20:06:52 26 4
gpt4 key购买 nike

有人可以帮我解决这个问题吗?我需要通过系统 DSN 检查我与 AS400 服务器的 ODBC 连接,如果不存在特定的系统 DSN,则创建一个系统 DSN。我试过谷歌搜索,但没能找到对我有好处的东西。

顺便说一句,我对编程还很陌生。任何帮助都感激不尽。谢谢

最佳答案

在浏览了几个不太复杂的在线示例之后,这就是我设法想出的(对我来说效果很好)。

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

关于c# - 检查系统 DSN 并创建系统 DSN(如果不存在)(iSeries Access ODBC 驱动程序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9256368/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com