CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Dec 2009
    Posts
    90

    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?

  2. #2
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    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.

  3. #3
    Join Date
    Sep 2008
    Location
    Netherlands
    Posts
    865

    Re: Reading from a SQL Server Database

    Quote Originally Posted by Arjay View Post
    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.

  4. #4
    Join Date
    Dec 2009
    Posts
    90

    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
  •  





Click Here to Expand Forum to Full Width

Featured