Dot-Net

如何將 sid 和埠包含到 oracle 連接字元串中?

  • February 14, 2018

我想在連接字元串中指定埠和 sid。以下程式碼執行後

public static string ConnectionString
{
   get
   {
       string host = Config.CsHost;
       string sid = Config.CsSID;
       string port = Config.CsPort;
       string user = Config.CsUser;
       string pass = Config.CsPassword;
       return String.Format(@"Data Source = {0}:{1}\{2}; Persist Security Info = True; User Id = {3}; Password = {4}; Unicode = True", host, port, sid, user, pass);
   }
}

using (OracleConnection connection = new OracleConnection(ConnectionString))
{
   try
   {
       connection.Open();

Open() 沒有響應…問題出在我認為的 sid 上。可能是什麼問題?

更新:我應該使用這種連接字元串。但我不能很好地解釋它。

數據源=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=MyHost)(PORT=MyPort)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=MyOracleSID))); 使用者 ID=我的使用者名;密碼=我的密碼;

有人可以幫我解釋一下嗎?

我不得不將 SERVICE_NAME 替換為 SID,所以:

return String.Format("SERVER=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST={0})(PORT={1}))(CONNECT_DATA=(SID={2})));uid={3};pwd={4};", host, port, sid, user, pass);

成功了。

讓我們把你在這裡的東西

Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=MyHost)(PORT=MyPort)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=MyOracleSID))); 
User Id=myUsername;
Password=myPassword;

這是.net連接字元串 這部分在這裡

(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=MyHost)(PORT=MyPort)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=MyOracleSID))) 

是oracle客戶端需要連接到SID。這部分也可以在TNS Names文件中配置。在這種情況下,您將有類似的東西

MyOraDbConnection = (DESCRIPTION=(ADDRESS_LIST=...

所以你的.net程式碼看起來像

string connStr = "Data Source=MyOraDbConnection;User Id=myUsername;Password=myPassword;"

2

現在,看起來你想要動態地做一些事情。通常,人們採用一堆文本框值並將它們連接起來

string dataSource = "(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=" + txtDbServer.Text + ...

另一種方法是

string dataSource = string.Format("(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST={0})(PORT={1})))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME={2})))",
   txtDbServer.Text,
   txtPort.Text,
   txtSid.Text);

或者,您可以創建 ConnStr 對象,它可以做的不僅僅是連接字元串。它可能會保存您的 conn 字元串 - 在虛擬碼中

class ConnStr
{
   string Server {get;set;}
   string Port {get;set;}
   string Sid {get;set;}
   // more properties

   string GetConnectionString()
   {
       // return your compiled string
   }

   void Save(string switches)
   {
       // Save your string to different places. 
       // For example 
       //      /f myconnfile.txt - will save to application root directory
       //      /f c:\xxx\myconnfile.txt - will save to specific directory
       //      /s myconnsetting  - will save to settings
   }

   void Load(string switches)
   {
       // Load your string from sources. 
   }
}

這是更多的工作,但也更靈活

引用自:https://stackoverflow.com/questions/27723223