How to read data (data reader) from the database in C ),

Source: Internet
Author: User

How to read data (data reader) from the database in C ),
To query data in the database through statements in C #

SqlConnection con = null; // the object for creating SqlConnection

Try // put the code that may contain errors
{

String str = "data source =.; initial catalog = database name; user ID = login name; pwd = password ;";

Con = new SqlConnection (str );

Con. Open (); // Open the database
 
// The preceding operations are performed to log on to the database.

String SQL = "select column name 1, column name 2, column name 3, column name 4, column name 5 from QQuser where query condition;

SqlCommand com = new SqlCommand (SQL, con );

SqlDataReader read = com. ExecuteReader (); // use the ExecuteReader () method on the com (variable name) point. The type of this method is SqlDataReader.

While (read. Read () // The Read () method on the variable name. Use a loop to ensure that all data in the database can be read.
// If data exists in the next row of the current pointer in the database, the Read () method returns true, and false if no data exists.
{

Int number = Convert. toInt32 (read ["column name 1"]); // query the data of column name 1 by: read (variable name) ["column name"]; this method returns the object type

String name = read ["column name 2"]. ToString (); // As shown above

String revise = read ["column name 3"]. ToString ();

String Email = read ["column name 4"]. ToString ();

Int day = Convert. ToInt32 (read ["column name 5"]);

Console. writeLine ("{0} \ t {1} \ t {2} \ t {3} \ t {4}", number, name, revise, Email, day );

}
}
Catch (Exception) // if an error occurs in try, execute the code in catch; otherwise, do not execute

{

Console. WriteLine ("network exception! ");

}

Finally // execute the code in finally anyway

{

If (con! = Null) // judge whether con is not empty

{

Con. Close ();

}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.