2014-09-27 231 views
0

在c#窗體窗體中,如果我想在整個應用程序中訪問它,我應該在哪裏放置我的sql連接字符串變量? 現在我正在複製它粘貼到哪裏,我使用它。c#sql連接字符串變量?

// SQL連接字符串

SqlConnection con = new SqlConnection(@"Data Source=" + globalvariables.hosttxt + "," + globalvariables.porttxt + "\\SQLEXPRESS;Database=ha;Persist Security Info=false; UID='" + globalvariables.user + "' ; PWD='" + globalvariables.psw + "'"); 
SqlCommand command = con.CreateCommand(); 

回答

0

那是一個相當普遍的問題,IMO ..取決於應用程序的結構等。我傾向於使用具有這些屬性的類「ApplicationContext」。然而,也許

ConfigurationManager.ConnectionStrings["whatever"].ConnectionString 

使用了很多,我認爲(添加引用System.Configuration)

順便說一句,如果你使用它「所有的地方」,並不需要一個適配器類,而不是?

編輯

public class DataAcces 
{ 
    private string Connectionstr; 
    public DataAcces() 
    { 
     this.Connectionstr = ConfigurationManager.ConnectionStrings["whatever"].ConnectionString; 
    } 
    public object ReturnSomething() 
    { 
     using(SqlConnection con = new SqlConnection(this.Connectionstr)) 
     { 
     //do stuff to db and return something 
     } 
    } 
} 

,然後當你需要它

.... 
{ 
    var whatYouNeed = (new DataAcces()).ReturnSomething(); 
} 

錯別字發生:)這是最容易使用的,我可以想出,沒有最好。

+0

我有3個表格都使用需要連接字符串的sql查詢。 – user3888775 2014-09-27 12:27:56

+0

當你說適配器類時,你的意思是創建一個全局連接字符串。像我的一些字符串已經有「globalvariables」? – user3888775 2014-09-27 12:31:16

+0

不,我的意思是一個可以響應所有數據訪問的類。因此所有的sql都是在該類中定義的。 – user1515791 2014-09-27 12:34:31

1

您可以簡單地使用app.config(或web.config)。它有一個連接字符串的特殊部分。 See the MSDN-article about that.然後你可以檢索代碼字符串作爲use1515791已經指出,像這樣:

ConfigurationManager.ConnectionStrings["NameOfConnectionStringInConfig"].ConnectionString 
1

我寧可不使用app.config文件,因爲它並不安全,容易被破解(每個連接的信息是存儲在純文本格式在這裏)。

如果我沒有使用我的DLL中的任何一個,我將SqlConnection放在Program.cs中,並使用public getter和disabled setter。我使Program.cs中所有的初始化,所以它看起來是這樣的:從您Form1.cs中

static class Program 
    { 
     private static SqlConnection con; 
     internal static SqlConnection Con 
     { 
      get 
      { 
       return con = new SqlConnection(@"Data Source=" + globalvariables.hosttxt + "," + globalvariables.porttxt + "\\SQLEXPRESS;Database=ha;Persist Security Info=false; UID='" + globalvariables.user + "' ; PWD='" + globalvariables.psw + "'"); 
      } 
     } 

     [STAThread] 
     static void Main() 
     { 
      Application.EnableVisualStyles(); 
      Application.SetCompatibleTextRenderingDefault(false); 
      Application.Run(new Form1()); 
     } 
    } 

現在可以訪問它(例如):

public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 

      SqlCommand cmd = new SqlCommand(); 
      cmd.Connection = Program.Con; 
     } 
    } 

我已經創建了一個DLL很容易連接到SQL,如果您有興趣,請檢查它here