|
-
December 5th, 2009, 05:12 PM
#1
Reading from a SQL Server Database
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?
-
December 5th, 2009, 06:13 PM
#2
Re: Reading from a SQL Server Database
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.
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.
-
December 6th, 2009, 06:04 AM
#3
Re: Reading from a SQL Server Database
 Originally Posted by Arjay
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.
-
December 6th, 2009, 11:53 AM
#4
Re: Reading from a SQL Server Database
Thanks a bunch , worked perfectly
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|