主要代码如下:
//连接字符串 string strConn="user id=sa;password=123456;initial catalog=MyDb;Server=192.168.47.144,1433;Connect Timeout=10"; //创建连接对象 SqlConnection objConn = new SqlConnection(strConn);
try { //开始连接数据库 objConn.Open();
//执行SQL语句 string sql = "SELECT * FROM tb_People"; SqlCommand sqlCom = new SqlCommand(sql,objConn);
//创建数据读取器对象,注意:该对象只能顺序读取记录 SqlDataReader sqlDataReader = sqlCom.ExecuteReader();
//循环输出记录 int i = 1; while(sqlDataReader.Read()){
Console.WriteLine("\n表tb_People第{0}条记录为:{1}{2}", i, sqlDataReader.GetValue(0), sqlDataReader.GetValue(1)); i++; } //断开与数据库的连接... objConn.Close(); } //捕获异常... catch(SqlException e){
objConn.Close();
Console.WriteLine(e.Message+e.ErrorCode);
}