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 Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Reading Data from SQL Server 2005 (Express Edition) 1

Status
Not open for further replies.

hspage

Programmer
Jun 9, 2008
12
US
Greetings,

I am attempting to read data from a SQL Server 2005 table. I have the following code below but I'm obviously missing something. When I put a watch on the variable, "strData", the value is the following:

"System.Data.SqlClient.SqlDataReader"

Code:

SqlConnection conn = new SqlConnection("Data Source=HOME-PC\\SQLEXPRESS;Initial Catalog=Contacts;Integrated Security=True");
conn.Open();
SqlCommand sql = new SqlCommand();
sql.CommandText = "SELECT * FROM tblContacts";
sql.Connection = conn;
string strData;
System.Data.SqlClient.SqlDataReader rd;
rd = sql.ExecuteReader();
while (rd.Read()==true)
{
strData = rd.ToString();
}
rd.Close();

What am I missing?

Thanks in advance!
 
rd.ToString() returns the type of object that it is, a SqlDataReader. SqlDataReader returns an array of objects. you are trying to put that into a string.

instead you need to populate another object and cast the values. Whether that object is a DataSet/Table, ArrayList or a custom POCO (Customer class) is up to you.

also, do a search for good ado.net practices. there is alot of potential here for errors. the biggest one is you're missing a try/finally block to close/dispose of objects if there is an exception while connecting to the db.

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top