I tried this code to test the connection if open or not to work on the same connection in all the website :

try
{
    con =  ( con == null ? new SqlConnection() : con );
    if (con.State != System.Data.ConnectionState.Open)
        con.Open();

    SqlCommand com = new SqlCommand(query, con);
    int result = com.ExecuteNonQuery();
    con.Close();
    return result;
}
catch (SqlException odbcEx)
{
    return 0;
}

but its give that error : System.InvalidOperationException: The ConnectionString property has not been initialized.

in the con.Open(); line .... any help ?

有帮助吗?

解决方案

A connection, to be opened, need to know where is located the server, what database you want to open and other administrative information. Your code doesn't supply these info when you call the constructor of the SqlConnection. You need to pass a connectionstring.

con =  ( con == null ? new SqlConnection(connectionString) : con );
if (con.State != System.Data.ConnectionState.Open)
    con.Open();

An example of a connection string is:

string connectionstring = @"Server=serverName;Database=dbName;
                            User Id=userName;Password=password;"

Other examples of a connection string could be found at this site

其他提示

string str = @"DataSource=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\sss.mdf;Integrated Security=True; Max Pool Size=100; User Instance=True";

try
{
    con =  ( con == null ? new SqlConnection(str) : con );
    if (con.State != System.Data.ConnectionState.Open)
    {
        con.Open();
    }
    SqlCommand com = new SqlCommand(query, con);
    int result = com.ExecuteNonQuery();
    con.Close();
    return result;
}
catch (SqlException odbcEx)
{
    return 0;
}

missing the connection string

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top