Sunday, February 12, 2012

Connection property not initialized

Hi,

I'm trying to do a database operation in ASP.NET page using the following code:

string connString = "SERVER=localhost;DATABASE=chbr;UID=sa;PWD=password;Connection Timeout=120";
SqlConnection sqlConn = new SqlConnection(connString);
sqlConn.Open();

string commandStr = "...";

SqlCommand command = new SqlCommand(commandStr);

command.ExecuteNonQuery();
sqlConn.Close();

But I kept getting the exception saying "ExecuteNonQuery: Connection property has not been initialized."

What did I do wrong?

Thanks!

You should be doing as much of the "busy work" as possible before you open the connection. Also, you should use either the using statement or a try / finally block.You did not specify which SQL connection the SqlCommand is supposed to use, which is why you got that error.

SqlConnection sqlConn = null;

try
{
string connString = "SERVER=localhost;DATABASE=chbr;UID=sa;PWD=password;Connection Timeout=120";
sqlConn = new SqlConnection(connString);

string commandStr = "...";

SqlCommand command = new SqlCommand(commandStr, sqlConn);

sqlConn.Open();
command.ExecuteNonQuery();
}
finally
{
if (sqlConn != null)
{
if (sqlConn.State == ConnectionState.Open)
{
sqlConn.Close();
}
}
}

No comments:

Post a Comment