C#初学二 14 SqlDataReader的使用

    技术2022-07-11  71

    static void Main(string[] args) { string constr = "Data Source =.;Initial Catalog = Person;User ID =sa; Password =sa "; using (SqlConnection con = new SqlConnection(constr)) { string sql = "select *from Student"; using (SqlCommand cmd = new SqlCommand(sql, con)) { con.Open(); 通过调用ExecuteReader()方法,将给定的SQL语句再服务器端执行。 执行完毕后,服务器端就已经查询出了数据。但是数据是保存在数据库服务器的内存当中。 没有返回给应用程序。只是返回给应用程序一个reader对象,这个对象就是用来获取数据的对象。 using (SqlDataReader reader = cmd.ExecuteReader()) { 接下来就要通过reader对象一条一条获取数据 1.在获取数据之前,先判断一下本次执行查询后,是否查询到了数据。 if (reader.HasRows) 如果有数据,则为trul { 2.如果有数据,那么接下来就要一条一条获取数据 每次获取数据前,都要先调用reader.Read()方法,向后移动一条数据,如果成功移动到了某条数据上,则返回true,否则返回false while (reader.Read()) { 获取Reader指向的数据 reader.FieldCount ,可以获取当前查询语句查询出的列的个数。 for (int i = 0; i < reader.FieldCount; i++) { Console.WriteLine(reader[i]+" |"); } } Console.ReadKey(); } else { Console.WriteLine("没有查询到任何数据!!!"); } } } } }

    Processed: 0.010, SQL: 9