Calling an SQL Connection method in C#

僤鯓⒐⒋嵵緔 提交于 2019-12-24 13:14:23

问题


I am calling this method to my Login Form. I don't know what is wrong with this. I've created a class named MyConnection and this class contains my SQL ConnectionString. What i want is I can call this function ex. Class1 method named Myfunction would be called to my Login Form so calling a connection string would be faster.

public static class MyConnection
{
    public static SqlConnection getConnection()
    {                
        string conn = "Data Source=EDGAR-PC\\SQLEXPRESS;Initial Catalog=Project1;Integrated Security=True";
        SqlConnection myConn = new SqlConnection(conn);
        return myConn;    
    }    
}

回答1:


You can't instantiate the static class. You can call it like this:

using (var connection = MyConnection.getConnection())
{
    connection.Open();
    //do whatever you need
}



回答2:


Since the static class cannot be instantiated, you will have to call like this:

private static void OpenSqlConnection(string connectionString)
    {
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();
        }
    }


来源:https://stackoverflow.com/questions/15793266/calling-an-sql-connection-method-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!