Part 1 database sql server c# Làm quen với việc kết nối cơ sở dữ dữ liệu

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; namespace Ke_noi_co_so_du_lieu_database_part1 { class Program { static void Main(string[] args) { SqlConnection conn = new SqlConnection(@"Data Source=QGPDGJK8S6DWF6S;Initial Catalog=Qlhocsinh;Integrated Security=True");///kết nối với cơ sở dữ liệu ;tren database sql server Console.Write("Lenh thuc thi dk khoi tao");// sau khi kết nối câu lệnh dk thực thi try { conn.Open();// mở kết nối Console.Write("ket noi thanh cong"); string sql = @"select COUNT(*) from HocSinh h where hs.Tenhocsinh = 'lvchuc' ";/// câu lệnh thực thi chạy điếm số lượng học sinh co ten la lvchuc SqlCommand CMD = new SqlCommand(sql,conn);//// kết nối câu blệnh thực thi với database Console.Write("\ncau lenh dang dk chay la: "+CMD.CommandText);// chạy câu lệnh thực thi đó ra Console.Write("\nso luong sinh vien co ten la le van chuc: "+CMD.ExecuteScalar());///cơ chế đếm số lượng ExecuteScalar() string sql2 = @"select COUNT(*) from HocSinh hs where hs.Tenhocsinh='lvchuc' and hs.Diem>8 and hs.Malop='d1'";///tạo câu lệnh thực thi 2 cũng là đếm số lượng học sinh nhưng cón 2 điều kiện thêm CMD = new SqlCommand(sql2, conn);///////kết nối câu lệnh thực thi 2 với database Console.Write("Ten hoc sinh la le van chuc diem >8 va la lop d1"+CMD.ExecuteScalar());// chay theo cơ chế ExecuteScalar() là đếm số lượng } catch(SqlException e) { Console.WriteLine(e.ToString());// chạy khi trong try có lỗi xãy ra } finally { conn.Close(); Console.Write("Ngat ket noi");// cho dù try co lỗi thì funally vẫn chạy bình thưởng } Console.ReadKey();/// dừng màn hình như system("pause"); } } }

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.