- Using System;
- Using System.Collections.Generic;
- Using System.Linq;
- Using System.Text;
- Using System.Data.SqlClient;
- Namespace Login
- {
- Class Program
- {
- static void Main (string[] args)
- {
- //Create a new database connection
- using (SqlConnection conn = new SqlConnection (Getconnectstring ()))
- {
- Conn. Open (); //Open Database
- //console.writeline ("Database open successfully!");
- //CREATE DATABASE command
- SqlCommand cmd = conn. CreateCommand ();
- //Create query Statements
- Cmd.commandtext = "SELECT * from UserInfo";
- //Read data stream from the database into reader
- SqlDataReader reader = cmd. ExecuteReader ();
- //Read the next line of data from reader, if there is no data, reader. Read () returns flase
- While (reader. Read ())
- {
- //reader. GetOrdinal ("id") is the index of the column in which the ID is obtained .
- //reader. GetInt32 (int n) This is the data in the nth column returned in the format Int32
- //reader. GetString (int n) This is the data in column n is returned in string format
- int id = reader. GetInt32 (reader. GetOrdinal ("id"));
- String name = Reader. GetString (reader. GetOrdinal ("name"));
- string pwd = reader. GetString (reader. GetOrdinal ("password"));
- int age = Reader. GetInt32 (reader. GetOrdinal ("age"));
- string sex = reader. GetString (reader. GetOrdinal ("Sex"));
- string phone = reader. GetString (reader. GetOrdinal ("Phone"));
- string address = reader. GetString (reader. GetOrdinal ("Address"));
- //Format output data
- Console.Write ("id:{0},name:{1},pwd:{2},age:{3},sex:{4},phone{5},address:{6}\n", ID, Name, PWD, age, Sex, Phone, address);
- }
- }
- Console.readkey ();
- }
- //Get a database connection string
- static string getconnectstring ()
- {
- return "Data source= (local); Initial catalog=db1;integrated security=sspi;";
- }
- }
- }
Read data from the database and output