1 static void Main(string[] args) 2 { 3 //创建连接字符串 4 string constr = "Data Source=PENGYOUQIANG-PC;Initial Catalog=lianlian;Integrated Security=True"; 5 //创建连接对象 6 using (SqlConnection con = new SqlConnection(constr)) 7 { 8 //编写执行的SQL语句 9 string Sql = "select * from lianxi"; 10 //执行SQL语句 11 using(SqlCommand comm=new SqlCommand(Sql,con)) 12 { 13 //打开连接 14 con.Open(); 15 using (SqlDataReader reader=comm.ExecuteReader()) 16 { 17 //判断表中是否有数据 18 if (reader.HasRows) 19 { 20 //一行一行读取数据 21 while(reader.Read()) 22 { 23 Console.Write(reader.GetInt32(0)+" "); 24 Console.Write(reader.GetString(1) + " "); 25 Console.Write(reader.GetString(2) + " "); 26 Console.Write(reader.GetString(3) + " "); 27 //用GetXxxx方法来获取值,如果为NULL会报异常,此时需要手写代码来判断 28 //Console.WriteLine(reader.IsDBNull(4) ? "NULL" : reader.GetInt32(4)); 29 Console.Write(reader.GetInt32(4)); 30 Console.WriteLine(); 31 } 32 Console.ReadKey(); 33 } 34 } 35 } 36 } 37 }
时间: 2024-10-10 01:10:39