bbcompent1 bbcompent1 - 1 month ago 9
C# Question

Attempting to open SQL Connection from console application - conn.open dies

My code gets to conn.Open and gives me "Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll"

Here is the block of code:

_timer.Stop();
string path = @"C:\testlog.log";
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MYDB_Conn"].ConnectionString);
string query = "SELECT RawImportEnabled, ImportDayTimeStamp from Settings";
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open(); // Dies here
SqlDataReader rdr = cmd.ExecuteReader();

Answer

Order is missing ...first open connection then use sql command

_timer.Stop();
        string path = @"C:\testlog.log";
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MYDB_Conn"].ConnectionString);
        conn.Open(); // sholud be here

        string query = "SELECT RawImportEnabled, ImportDayTimeStamp from Settings";
        SqlCommand cmd = new SqlCommand(query, conn);
        SqlDataReader rdr = cmd.ExecuteReader();

Besides your code is not formatted either..Format like this

 string path = @"C:\testlog.log";
            String connectionString = ConfigurationManager.ConnectionStrings["MYDB_Conn"].ConnectionString;
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                conn.Open(); // sholud be here

                string query = "SELECT RawImportEnabled, ImportDayTimeStamp from Settings";
                SqlCommand cmd = new SqlCommand(query, conn);
                SqlDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                { 
                    String RawImportEnabled = Convert.ToString(reader["RawImportEnabled"]);
                    //Do some thing
                }
            }

This has some benefits like debugging the connection string by putting a breakpoints ,Disposal of connection without worrying for using statements etc

Comments