Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

C# newbee 'System.Data.SqlClient.SqlException'

Status
Not open for further replies.

other3

Programmer
Jul 30, 2002
92
US
public ArrayList GetProducts()
{
ArrayList alProducts = new ArrayList();

string strSelect = "SELECT ProductCode, Description, "
+ "UnitPrice FROM Products";

SqlConnection theSqlConnection = Connection();

SqlCommand theSqlCommand = new SqlCommand(strSelect,
theSqlConnection);

theSqlConnection.Open();

SqlDataReader productReader;

// would love to know why the following is giving me
// the exception
productReader = theSqlCommand.ExecuteReader();

while (productReader.Read())
{
alProducts.Add(productReader["ProductCode"]);
alProducts.Add(productReader["Description"]);
alProducts.Add(productReader["UnitPrice"]);
}

productReader.Close();
theSqlConnection.Close();

return alProducts;
}

Everything else works great until it gets to the reader.



Everything I know I learned from The Grateful Dead and Buffy The Vampire Slayer
Charlie
 
I suggest you do this:


try
{

productReader = theSqlCommand.ExecuteReader();

while (productReader.Read())
{
alProducts.Add(productReader["ProductCode"]);
alProducts.Add(productReader["Description"]);
alProducts.Add(productReader["UnitPrice"]);
}

//Remove these...
// productReader.Close();
// theSqlConnection.Close();


}
catch( Exception anException)
{
//Log the anException.Message to see the error...
}
finally
{
productReader.Close();
if( theSqlConnection.State == ConnectionState.Open)
theSqlConnection.Close();
}


This way, you will get the exception, see what went wrong, and also you will ensure that you close the reader and the connection which is very important and which is not happening in your case if an exception is thrown... [thumbsup2]

If the exception message does not give you any hint, post it as a reply here...
 
Thanks much, it's a permission denied on reading from the database. I'll be able to work that out.

Everything I know I learned from The Grateful Dead and Buffy The Vampire Slayer
Charlie
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top