Click to See Complete Forum and Search --> : Reading from a SQL Server Database


dovobet
December 5th, 2009, 04:12 PM
hi

Im trying to read data from a database on an SQL Server ( not compact) but I keep having the problem with the code

SqlCommand readAccounts = new SqlCommand
("SELECT * from sahebfp9_Accounts", connectionLine);

reader = readAccounts.ExecuteReader();
string tempUsername = reader.GetString(1).Trim();


The bottom line throws a InvalidOperationException and says {"Invalid attempt to read when no data is present."} but I do have data in the database table.

Can somebody help?

Arjay
December 5th, 2009, 05:13 PM
A good thing to do when starting on this technology is to get familar with Msdn which is a great source for .net namespaces, classes, methods and basic usage information.

From msdn:

SqlCommand.ExecuteReader( ) method (http://msdn.microsoft.com/en-us/library/9kcbe65k.aspx).

The problem in your case is that you need to call the SqlDataReader.Read( ) method before calling the reader.GetString method.

As an aside, I noticed that your code uses the Trim() method after retrieving the string from the database. You might consider (if possible) using a strategy where only trimmed, clean data is put into the database. That way, when you read the data, you won't need to worry about cleaning the data before using it.

dannystommen
December 6th, 2009, 05:04 AM
As an aside, I noticed that your code uses the Trim() method after retrieving the string from the database. You might consider (if possible) using a strategy where only trimmed, clean data is put into the database. That way, when you read the data, you won't need to worry about cleaning the data before using it.


It also saves diskspace and performance.

dovobet
December 6th, 2009, 10:53 AM
Thanks a bunch , worked perfectly:)