Create SQL Server DSN

本文关键字:DSN Server SQL Create | 更新日期: 2023-09-27 17:52:34

我需要通过代码创建一个DSN与SQL Server连接。我尝试了这个链接中的例子,但它总是失败,因为dataSourceKey永远不会为空。有人有不同的解决方案或其他选择吗?

http://www.codeproject.com/Tips/350601/Create-SQL-DSN-in-Csharp

这是代码:

string ODBC_PATH = "SOFTWARE''ODBC''ODBC.INI''";     
string driverName = "SQL Server";
string dsnName = "DSNfromCode";
string database = "MyDBName";
string description = "This DSN was created from code!";
//This is one change I made the source code had the IP of the server and I 
//am hardcoding a server name
string server = "Brimstone";
bool trustedConnection = false;
// Lookup driver path from driver name         
string driverPath = "C:''WINDOWS''System32''sqlsrv32.dll"; 
var datasourcesKey = Registry.LocalMachine.CreateSubKey(ODBC_PATH + "ODBC Data Sources");         
if (datasourcesKey == null) 
{
throw new Exception("ODBC Registry key does not exist"); 
}        
    datasourcesKey.SetValue(dsnName, driverName);          
    // Create new key in odbc.ini with dsn name and add values        
    var dsnKey = Registry.LocalMachine.CreateSubKey(ODBC_PATH + dsnName);        
    if (dsnKey == null) 
{
throw new Exception("ODBC Registry key for DSN was not created"); 
}             
dsnKey.SetValue("Database", database);         
dsnKey.SetValue("Description", description);         
dsnKey.SetValue("Driver", driverPath);         
dsnKey.SetValue("LastUser", "sa");         
dsnKey.SetValue("Server", server);         
dsnKey.SetValue("Database", database);
dsnKey.SetValue("username", "sa");
dsnKey.SetValue("password", "system123#");
dsnKey.SetValue("Trusted_Connection", trustedConnection ? "Yes" : "No");

Create SQL Server DSN

我最终只是从我的PC上导出注册表键,然后在需要它的PC上的loaddevent()上启动它