2014-09-27 230 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