问题
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