Giáo trình Hệ quản trị cơ sở dữ liệu MSSQL 2005 - Chương 8: Kết nối với SQL Sercver và ứng dụng trên C#

private void RefreshDataGrid() { try { conn.Open(); SqlCommand cmd = new SqlCommand("usp_GetALL_Sinhvien", conn); cmd.CommandType = CommandType.StoredProcedure; SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds, "SV"); dataGridView1.DataSource = ds.Tables["SV"]; conn.Close(); } catch (Exception ex) { throw new Exception(ex.Message.ToString()); } } private void Capnhat_sv_Load(object sender, EventArgs e) { RefreshDataGrid(); }

ppt22 trang | Chia sẻ: huongthu9 | Lượt xem: 359 | Lượt tải: 0download
Bạn đang xem trước 20 trang tài liệu Giáo trình Hệ quản trị cơ sở dữ liệu MSSQL 2005 - Chương 8: Kết nối với SQL Sercver và ứng dụng trên C#, để xem tài liệu hoàn chỉnh bạn click vào nút DOWNLOAD ở trên
Chương 8 KẾT NỐI VỚI SQL SERVER & ỨNG DỤNG TRÊN C# KHOA CÔNG NGHỆ THÔNG TINI. Cấu hình của SQL ServerClick Start -> Programs -> Microsoft SQL Server 2005 -> Configuration Tools -> SQL Server Surface Area Configuration. Trong trang SQL Server 2005 Surface Area Configuration, click Surface Area Configuration for Services and Connections. Trong trang Surface Area Configuration for Services and Connections, mở nút Database Engine, click Remote Connections, click Local and remote connections, click chọn giao thức thích hợp chúng ta thường dùng giao thức TCP/IP, sau đó click Apply. Lưu ý: Click OK khi nhận được thông báo:Changes to Connection Settings will not take effect until you restart the Database Engine service.Trong trang Surface Area Configuration for Services and Connections, mở nút Database Engine, click Service, click Stop, đợi đến khi dịch vụ MSSQLSERVER dừng lại, sau đó click Start để khởi động lại dịch vụ MSSQLSERVER1. Tiếp cận kết nối từ xa với SQL 2005Kết nối từ xa với SQL 20082 Kích hoạt dịch vụ SQL Server Browser 2005Nếu chúng ta thao tác trên SQL Server 2005 bằng việc sử dụng tên thể hiện (instance name) và không chỉ định một port cụ thể trong chuỗi kết nối thì chúng ta phải kích hoạt dịch vụ SQL Server Browser để cho phép các kết nối từ xa. Ví dụ: SQL Server 2005 Express Edition được cài đặt với một thể hiện mặc định là tên_máy_tính\SQLEXPRESS. Chúng ta chỉ cần kích hoạt dịch vụ SQL Server Browser một lần bất kể chúng ta có bao nhiêu thể hiện của SQL Server 2005 đang được sử dụng (running). Để kích hoạt dịch vụ SQL Server Browser, cần làm theo các bước sau:Click Start -> Programs -> Microsoft SQL Server 2005 -> Configuration Tools, click SQL Server Surface Area Configuration.Trong trang SQL Server 2005 Surface Area Configuration, click Surface Area Configuration for Services and Connections.Trong trang Surface Area Configuration for Services and Connections, click SQL Server Browser, click Automatic for Startup type, click Apply.Kiểm tra tình trạng dịch vụ trong Service status. Sau đó click Start nếu dịch vụ này đang bị Stop.3. Tạo các ngoại lệ trên Windows Firewall 2005Các bước dưới đây áp dụng cho Windows Firewall trong Windows XP Service Pack 2 (SP2) và trong Windows Server 2003.Nếu tường lửa được sử dụng trên máy tính cài đặt SQL Server 2005, các kết nối từ bên ngoài sẽ bị chặn trừ khi SQL Server 2005 và SQL Serve Browser có thể liên lạc qua tường lửa. Chúng ta phải tạo ra các ngoại lệ cho mỗi thể hiện của SQL Server 2005 (muốn thể hiện nào tiếp nhận kết nối từ xa thì chúng ta phải tạo ngoại lệ cho thể hiện đó) và một ngoại lệ cho dịch vụ SQL Server Browser.Việc tạo ngoại lệ theo các bước sau:Click Start -> Programs -> Microsoft SQL Server 2005 ->Configuration Tools -> SQL Server Configuration Manager. Trong trang SQL Server Configuration Manager, click SQL Server Services, right-click tên thể hiện, và click Properties. Trong trang SQL Server Browser Properties, click tab Advanced, xác định instanceID trong danh sách thuộc tính, và click OK.Lưu ý: - Nếu chúng ta không cần sử dụng SQL Server 2005 thường xuyên, ta có thể để chế độ khởi động của dịch vụ MSSQLSERVER là manual (nghĩa là khi nào cần dùng thì sẽ kích hoạt) nhằm giảm bớt thời gian khởi động Windows và tiết kiệm tài nguyên hệ thống.. - Tương tự như dịch vụ MSSQLSERVER, nếu chọn startup type là Automatic thì dịch vụ SQL Server Browser sẽ được khởi động khi Windows khởi động. - Chúng ta có thể có nhiều thể hiện SQL Server, do đó chúng ta phải xác định đúng instanceID nào chúng tao muốn tạo ngoại lệ. Để mở Windows Firewall, click Start, click Run, đánh firewall.cpl, và click OK. Tạo ngoại lệ cho SQL Server 2005 trong Windows Firewall Trong Windows Firewall, click tab Exceptions, sau đó click Add Program. Trong cửa sổ Add a Program window, click Browse. C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Binn\sqlservr.exe, click Open, và click OK.II. KẾT NỐI SQL VỚI C#Thao tác tìm chuỗi kết nốiKhởi động C# (nếu chưa khởi động)Chọn View -> Server Explore (nếu chưa có)Right_Click vào Data Conection, chọn Add ConnectNhập các giá trị: Server Name, Database Name.Chọn Test ConnectRight_Click vao tên kết nối, chọn PropertiesVào thuộc tính Connect String: tìm thấy chuỗi kết nối sau: Kết nối với chứng thực Windows Authentication Data Source=;Initial Catalog=; Integrated Security=True Kêt nối với chứng thực MixMode Data Source=;Initial Catalog=;Password=2. Viết chuỗi kết nối trong C#Ví dụ: Thiết kế Form_Ketnoi như sau:Codepublic Form_Ketnoi() { InitializeComponent(); } private static SqlConnection conn; private static String ConnectString = "Data Source=MOBI-E2D6A25F65;Initial Catalog=QLSV;Integrated Security=True"; private void button1_Click(object sender, EventArgs e) { try { conn = new SqlConnection(ConnectString); conn.Open(); MessageBox.Show("Kết nối thành công"); button2.Enabled = true; button3.Enabled = true; } catch (Exception ex) { MessageBox.Show("Kết nối thất bại"); } } private void button2_Click(object sender, EventArgs e) { String strStatus = "Closed"; if (conn.State==ConnectionState.Open) strStatus="Openned"; MessageBox.Show("Thông tin kết nối hiện tại là" + strStatus + " Tên Server là: " + conn.DataSource); } private void button3_Click(object sender, EventArgs e) { conn.Close(); MessageBox.Show("CSDL SQL đóng"); } }Ví dụ: Tạo Form hiển thị dữ liệu trên Form sau:Lấy dữ liệu từ thủ tục trong SQLTên thủ tụcprivate void btnGetData_Click(object sender, EventArgs e) { try { conn = new SqlConnection(ConnectString); conn.Open(); SqlCommand cmd = new SqlCommand("usp_GetALL_Sinhvien", conn); // Khởi tạo biến cmd với đối tượng SqlCommand để thực thi thủ tục ten usp_GETALL_Svlop trong csdl cmd.CommandType = CommandType.StoredProcedure; SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds, "SV"); dataGridView1.DataSource = ds.Tables["SV"]; conn.Close(); } catch (Exception ex) { throw new Exception(ex.Message.ToString()); } }Ví dụ 3Tạo thủ tục GetAll_svlopCREATE PROC GETALL_svlop@Malop varchar(10)AS BEGIN SELECT Masv,HoTen,Gioitinh,Ngaysinh,Dienthoai,Malop FROM SINHVIEN where MaLop=@MalopEndGọi thủ tục có tham số private void button1_Click(object sender, EventArgs e) { try { conn = new SqlConnection(ConnectString); conn.Open(); SqlCommand cmd = new SqlCommand("usp_GETALL_Svlop", conn);cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@maLop", txtmalop.Text.Trim())); // Khởi tạo biến @Malop nhận giá trị trên Text và truyền vào tham số của đối tượng cmd SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds, "SV"); dataGridView1.DataSource = ds.Tables["SV"]; conn.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } conn.Close(); }Ví dụ 4Taọ thủ tục Insert_SinhvienCREATE PROC [dbo].[usp_Inserrt_SinhVien] @masv varchar(10), @hoTen nvarchar(30),@maLop varchar(10) , @ngaysinh date,@Gioitinh nvarchar(5)AS BEGIN declare @gt bit set @gt=case @gioitinh when 'Nam' then 'true' else 'false' endINSERT INTO SINHVIEN(Masv, HoTen,MaLop,NgaySinh,Gioitinh) VALUES(@Masv, @hoTen, @MaLop,@ngaysinh,@Gt) END private void txtThem_Click(object sender, EventArgs e) { txtMasv.Text = " "; txtMaLop.Text = " "; txtHoTen.Text = " "; txtNgaysinh.Text = " "; txtGioitinh.Text = " "; txtMasv.Focus(); } private void txtLuu_Click(object sender, EventArgs e) { try { conn.Open(); SqlCommand cmd = new SqlCommand("usp_Inserrt_SinhVien", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@MaSV", txtMasv.Text.Trim())); cmd.Parameters.Add(new SqlParameter("@MaLop", txtMaLop.Text.Trim())); cmd.Parameters.Add(new SqlParameter("@HoTen", txtHoTen.Text.Trim())); cmd.Parameters.Add(new SqlParameter("@Ngaysinh", txtNgaysinh.Text.Trim())); cmd.Parameters.Add(new SqlParameter("@Gioitinh", txtGioitinh.Text.Trim())); cmd.ExecuteNonQuery(); RefreshDataGrid(); cmd.Dispose(); conn.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void RefreshDataGrid() { try { conn.Open(); SqlCommand cmd = new SqlCommand("usp_GetALL_Sinhvien", conn); cmd.CommandType = CommandType.StoredProcedure; SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds, "SV"); dataGridView1.DataSource = ds.Tables["SV"]; conn.Close(); } catch (Exception ex) { throw new Exception(ex.Message.ToString()); } }private void Capnhat_sv_Load(object sender, EventArgs e) { RefreshDataGrid(); }

Các file đính kèm theo tài liệu này:

  • pptgiao_trinh_he_quan_tri_co_so_du_lieu_mssql_2005_chuong_8_ket.ppt