且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在单独的类中创建连接字符串?

更新时间:2023-02-17 10:39:28

只需获取它:

Just fetch it:
string strConnect = ConnectionString.ConnectionString();



虽然我个人而言,我会把它变成静态属性而不是方法:


Though personally, I would make it a static property instead of a method:

public static class ConnectionString
        {
        public static string Constr { get; private set; }
        static ConnectionString()
            {
            Constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString.ToString();
            }
        }



并按照以下方式使用它:


And use it like this:

string strConnect = ConnectionString.Constr;









当我以这种方式编写代码时,你建议我无法打开和关闭连接?即



如果我写的话以下陈述






"when i write the code in that way you suggested i could not open and close the connection? i.e

if i write the following statement

string strConnect = ConnectionString.Constr;



如何打开和关闭连接字符串。



strConnect没有像strConnect.open()或strConnect这样的属性。关闭()



请帮我看看如何打开和关闭连接?




老实说,我不会那样做。

虽然你可以在那个类中创建一个静态SqlConnection,但它不一定是个好主意:SQL连接是一个稀缺资源而且它是一个非常非常好的主意确保尽快打开,使用,关闭和处理它们。并且由于某种原因(可能是错误)你连接是开放的,这可能会导致以后出现大问题。

而是使用静态连接字符串在需要时创建一个新的SqlConnection。例如:


how can i open and close the connection strings.

strConnect has no properties like strConnect.open() or strConnect.Close()

Please help me how to open and close the connections?"


To be honest, I wouldn't do it there.
While you can create a single static SqlConnection in that class, it's not necessarily a good idea: SQL connections are a scarce resource and it's a very, very good idea to ensure that they are opened, used, closed, and disposed as quickly as possible. And it you connection is left open for some reason (by an error perhaps) that can cause huge problems later on.
Instead, use the static connection string to create a new SqlConnection when you need it. For example:

using (SqlConnection con = new SqlConnection(ConnectionString.Constr))
    {
    con.Open();
    using (SqlCommand cmd = new SqlCommand("SELECT Id, description FROM myTable", con))
        {
        using (SqlDataReader reader = cmd.ExecuteReader())
            {
            while (reader.Read())
                {
                int id = (int) reader["Id"];
                string desc = (string) reader["description"];
                Console.WriteLine("ID: {0}\n    {1}", id, desc);
                }
            }
        }
    }

或者:

Or:

using (SqlConnection con = new SqlConnection(ConnectionString.Constr))
    {
    con.Open();
    using (SqlDataAdapter da = new SqlDataAdapter("SELECT MyColumn1, MyColumn2 FROM myTable WHERE mySearchColumn = @SEARCH", con))
        {
        da.SelectCommand.Parameters.AddWithValue("@SEARCH", myTextBox.Text);
        DataTable dt = new DataTable();
        da.Fill(dt);
        myDataGridView.DataSource = dt;
        }
    }

使用块确保连接在不再需要时立即关闭和处理,不管发生了什么。

The using block ensures that the connection is closed and disposed as soon as it is no longer needed, regardless of what else happens.