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 ();
}
}