part 5 kết nối với cơ sở dữ liệu database c# ExecuteReader(đọc bản )

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; namespace ExecuteXmlReader { class Program { static void Main(string[] args) { /// tạo mối kết nối SqlConnection connet = new SqlConnection(@"Data Source=QGPDGJK8S6DWF6S;Initial Catalog=Qlhocsinh;Integrated Security=True"); Console.Write("\nQua trinh dang duoc ke noi !"); try { Console.Write("\nket noi thanh cong!"); connet.Open(); string soluonghocsinh = @"SELECT * FROM HocSinh"; SqlCommand lenthuthi = new SqlCommand(soluonghocsinh, connet); Console.Write("\nLenh thuc thi duoc khoi tao!"); Console.Write("\nDanh sach cac ma so sinh vien dang co la: "); SqlDataReader doc = lenthuthi.ExecuteReader();// đã kết nối câu lệnh thực lthi thành công với database thì tạo 1 biến thcự hiện việc đọc //ExecuteReader() /* co chế này thì đọc nhưng đọc từng dòng trong bản ta cón thể đọc hết tất cả các bản cùng 1 lúc bạn xem ở part 6 nhak */ int diem = 1; while(doc.Read())// đọc cho đến khi nào không còn dòng nào để dọc được nữa thì dừng lại (trong 1 bản) { Console.Write("\nDu lieu dong thu "+diem++); Console.Write("\nMa hoc sinh: " + doc[0]);// đọc cột thứ nhất hoặc ta có thể ghi như sau doc["mahocsinh"] Console.Write("\nHo ten: " + doc[1]);//doc["tenhocsinh"] Console.Write("\nMa lop: "+doc[2]);//vv..v Console.Write("\nMa mon: "+doc[3]); Console.Write("\nDiem: "+doc[4]); } doc.Close();//luôn nhớ kết thúc việc đọc nếu không có bạn sẽ thấy hậu quả } catch (SqlException e) { Console.WriteLine(e.ToString()); } finally { Console.Write("\ndong ket noi"); connet.Close();// đóng kết nối } Console.ReadKey();// dừng màn hình } } }

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.