簡體   English   中英

創建SQL Server DSN

[英]Create SQL Server DSN

我需要通過代碼創建DSN以與SQL Server連接。 我在此鏈接中嘗試過該示例,但由於dataSourceKey永遠不會為null,因此它總是失敗。 有人有其他解決方案或其他選擇嗎?

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

我最終只是從PC導出注冊表項,然后在需要它的PC上的loadevent()上啟動它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM