Lập trình cơ sở dữ liệu ppt

18 327 0
Lập trình cơ sở dữ liệu ppt

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Lập trình cơ sở dữ liệu I. Đối tượng Sqlconnection Không gian tên sử dụng là : System.Data.SqlClient ; 1. Kết nối theo đặc quyền hệ điều hành Cú pháp 1 : Server = servername [ \InstanceName ]; Database = databasename; Integrated Security = SSPI; Cú pháp 1 : Server = servername[ \InstanceName ]; Database = databasename; Integrated Security = true; Cú pháp 3 : Server = servername [ \InstanceName ]; Initial Catolog = databasename; Integrated Security = true; • Chú ý : Tài khoản đăng nhập phải được khai báo trong phần Login 2. Kết nối theo đặc quyền SQL Server Cú pháp 1 (Chung) : Server = Servername[ \InstanceName ]; Database = Databasename; Use ID = Username; Password = YourPasword; [Connection Timeout = second;] [port = portno;] [Persist Security Info = true;] • Chú ý : Servername có thể là : (local) hoặc ( . ) hoặc (Địa chỉ IP) . Cú pháp 2 : Với dạng Attachment và phiên bản SQL Server 2005 (SQLEXPRESS) @”Data Source = (local)\SQLEXPRESS; AttachDbFilename = <Đường dẫn tới file Database>; Integrated Security = true; Use Instance = true”; 3. Tập tin lưu chuỗi kết nối Ta có thể sử dụng các định dạng *.ini hoặc *.txt để lư chuỗi kết nối . Tuy nhiên khi làm việc với .Net chúng ta nên sử dụng định dạng *.config đã được hố trợ sẵn. - Cú pháp 1: ?xml version="1.0" encoding="utf-8" ?> <configuration> <connectionStrings> <add name="SqlServer" connectionString= " Server = servername[ \InstanceName ]; Database = databasename; Integrated Security = true; " providerName ="System.Data.SqlClient"/> </connectionStrings> </configuration>  Cách đọc nội dung chuỗi kết nối theo cú pháp 1 ta sử dụng phương thức connectionStrings của lớp connectionStringSettings thuộc không gian tên System.Configuration; II. Đối tượng SQLCommand 2.1 Khai báo SqlCommand sqlCommand; 2.2 Khởi tạo Có 4 Constructor để khai báo khởi tạo đối tượng này + sqlCommand = new SqlCommand(); + sqlCommand = new SqlCommand(string CommandText); + sqlCommand = new SqlCommand(string CommandText,SqlConnection sqlConnection); + sqlCommand = new SqlCommand(string CommandText,SqlConnection sqlConnection,SqlTrasaction sqlTransaction); 2.3 Các thuộc tính 2.3.1 CommandText Cho phép khai báo một chuỗi phát biểu SQL Server VD : String strSQL = “Select * from TBLSinhvien”; sqlCommand = new SqlCommand(); sqlCommand.CommandText = strSQL; 2.3.2 CommandType Cho phép ta chọn một trong 3 giá trị enum là : Text,TableDirect,StoredProcedure VD: String strSQL = “spDanhsachSV”; sqlCommand = new SqlCommand(); sqlCommand.CommandText = strSQL;am sqlCommand.CommandType = CommandType.StoredProcedure; • Lưu ý khi thủ tục có tham số truyền vào thì ta có thể sử dụng đối tượng SqlParameterCollection hay SqlParameter 2.3.3 CommandTimeout Cho phép khai báo thời gian chờ thực thi phát biểu SQL được tính bằng giây VD : String strSQL = “spDanhsachSV”; sqlCommand = new SqlCommand(); sqlCommand.CommandText = strSQL; sqlCommand.CommandType = CommandType.StoredProcedure; sqlCommand.CommandTimeout = 30; 2.3.4 Connection Cho phép ta khởi tạo đối tượng sqlConnection mà không cần phải thông qua Constructor VD : String strSQL = “spDanhsachSV”; sqlCommand = new SqlCommand(); sqlCommand.CommandText = strSQL; sqlCommand.Connection = sqlConnection; sqlCommand.CommandType = CommandType.StoredProcedure; sqlCommand.CommandTimeout = 30; 2.4 Phương thức 2.4.1 Phương thức ExecuteNonQuery Thực thi các phát biểu SQL, thử tục nội tại, và nó trả về số bản ghi đựoc thực thi VD : sqlCommand.Connection = sqlConnection; sqlConnnection.Open(); String strSQL = “delete from TBLSinhvien where Masv = ‘SV0000001’”; sqlCommand = new SqlCommand(); sqlCommand.CommandText = strSQL; int records = sqlCommand.ExcuteNonQuery(); sqlConnection.Close(); sqlConnection.Dispose();  Thực hiện thêm , sửa , xoá một bản ghi : using System; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Windows.Forms; namespace DoituongSQLCommand { public partial class Form1 : Form { // Khai bao doi tuong sqlConnection SqlConnection sqlConnection = new SqlConnection(); string connectionString = @"server =QUYETNV87\SQLEXPRESS ;" + "database = Sinhvien ;" + "Integrated Security = True;"; public Form1() { InitializeComponent(); } private void btnSQLinsert_Click(object sender, EventArgs e) { try { sqlConnection.ConnectionString = connectionString; sqlConnection.Open(); String strSQL = "insert into TBLSinhvien(MaSV,Hoten,Gioitinh,Ngaysinh,Malop,M atinh) values('SV0000011','Trần Quốc Huy','Nam','07/19/1986','1900052','T09')"; SqlCommand sqlCommand = new SqlCommand(); sqlCommand.CommandText = strSQL; sqlCommand.Connection = sqlConnection; int i = sqlCommand.ExecuteNonQuery(); // Đóng kết nối sqlConnection.Close(); // Giải phóng kêt nối cơ sở dữ liệu sqlConnection.Dispose(); MessageBox.Show("Đã thêm " + i.ToString() + " bản ghi"); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void Form1_Load(object sender, EventArgs e) { } private void btnSQLupdate_Click(object sender, EventArgs e) { try { sqlConnection.ConnectionString = connectionString; sqlConnection.Open(); String strSQL = "Update TBLSinhvien set Matinh ='T15' where Matinh='T05'"; SqlCommand sqlCommand = new SqlCommand(); sqlCommand.CommandText = strSQL; sqlCommand.Connection = sqlConnection; int i = sqlCommand.ExecuteNonQuery(); // Đóng kết nối sqlConnection.Close(); // Giải phóng kêt nối cơ sở dữ liệu sqlConnection.Dispose(); MessageBox.Show("Đã cập nhật " + i.ToString() + " bản ghi"); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void btnSQLdelete_Click(object sender, EventArgs e) { try { sqlConnection.ConnectionString = connectionString; sqlConnection.Open(); String strSQL = "Delete TBLSinhvien where MaSV='SV0000011'"; SqlCommand sqlCommand = new SqlCommand(); sqlCommand.CommandText = strSQL; sqlCommand.Connection = sqlConnection; sqlCommand.CommandTimeout = 60; int i = sqlCommand.ExecuteNonQuery(); // Đóng kết nối sqlConnection.Close(); // Giải phóng kêt nối cơ sở dữ liệu sqlConnection.Dispose(); MessageBox.Show(i.ToString() + " bản ghi đã được xoá "); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void btnInsertAttach_Click(object sender,EventArgs e) { SqlConnection sqlConnection = new SqlConnection(); string connectionString = @"server=(local)\SQLEXPRESS ;" + @"AttachDbFilename =E:\LAPTRINH\Database\Sinhvien.mdf;" + @"Integrated Security = True;" + @"User Instance= true;"; sqlConnection.ConnectionString = connectionString; try { sqlConnection.Open(); String strSQL = "insert into TBLSinhvien(MaSV,Hoten,Gioitinh,Ngaysinh,Malop,M atinh) values('SV0000011','Trần Quốc Huy','Nam','07/19/1986','1900052','T09')"; SqlCommand sqlCommand = new SqlCommand(); sqlCommand.CommandText = strSQL; sqlCommand.Connection = sqlConnection; int i= sqlCommand.ExecuteNonQuery(); // Đóng kết nối sqlConnection.Close(); // Giải phóng kêt nối cơ sở dữ liệu sqlConnection.Dispose(); MessageBox.Show(""); } catch (Exception ex) { MessageBox.Show(ex.Message); } } } } 2.4.2 Phương thức ExecuteScalar Phương thức này thực thi phát biểu SQL Server giá trị trả về là kiểu đối tượng (object) Nó thường được dùng để lấy giá trị của tổng các mấu tin hay giá trị của cột hay hàng thứ nhất  Ví dụ : using System; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Windows.Forms; namespace ExecuteScalar { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnSelectCount_Click(object sender, EventArgs e) { SqlConnection conn = new SqlConnection(); string connectionString = @"server = (local)\SQLEXPRESS ;" + "database = Sinhvien;" + "Integrated Security = true;"; conn.ConnectionString = connectionString; try { conn.Open(); String strSQL = "Select count(*) from TBLSinhvien"; SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandText = strSQL; object obj = cmd.ExecuteScalar(); MessageBox.Show("Số bản ghi trong bảng TBLSinhvien là " + Convert.ToString(obj)); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void btnGiatricot_Click(object sender, EventArgs e) { SqlConnection conn = new SqlConnection(); string connectionString = @"server = (local)\SQLEXPRESS ;" + "database = Sinhvien;" + "Integrated Security = true;"; conn.ConnectionString = connectionString; try { conn.Open(); String strSQL = "Select [Hoten] from TBLSinhvien"; SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandText = strSQL; object obj = cmd.ExecuteScalar(); MessageBox.Show("Họ tên của SV đầu tiên bảng TBLSinhvien là " + Convert.ToString(obj)); } catch (Exception ex) { MessageBox.Show(ex.Message); } } } } Kết quả : 2.4.3 Phương thức ExecuteReader Khác với hai phương thức trên , phương thức này trả về tập các giá trị chỉ đọc một chiều và dùng đối tượng sqlDataReader để nắm dữ tập dữ liệu đó.  Ví dụ : Ta lấy ra 2 cột là mã sinh viên và Họ tên trong bảng TBLSinhvien using System; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Text; using System.Windows.Forms; namespace ExecuteReader { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnGetData_Click(object sender, EventArgs e) { SqlConnection conn = new SqlConnection(); string connectionString = @"server = (local)\SQLEXPRESS ;" + "database = Sinhvien;" + "Integrated Security = true;"; conn.ConnectionString = connectionString; try { // Mở kết nối cơ sở dữ liệu conn.Open(); // Khai báo và khởi tạo đối tượng SqlCommand SqlCommand cmd = new SqlCommand("Select * from TBLSinhvien", conn); //Khai báo đối tượng SqlDataReader SqlDataReader dr = cmd.ExecuteReader(); string str = "Mã sinh viên - Họ tên\r\n\n"; //Đọc từng bản ghi while (dr.Read()) { str += dr.GetString(0) + " - " + dr.GetString(1) + "\r\n"; } // Đóng và giải phóng đôi tưọng SqlDataReader dr.Close(); dr.Dispose(); MessageBox.Show(str); //Đóng và giải phóng kết nối cơ sở dữ liệu conn.Close(); conn.Dispose(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } } } K ết qu ả : 2.4.4 Phương thức ExcuteXmlReader Phương thức này tương tự như phương thức ExecuteReader nhưng nó trả về tập dữ liệu có định dạng XML và sử dụng đối tượng XMLReader để nắm dữ tập dữ liệu đó.  Ví dụ : Đọc bản ghi đầu tiên trong bảng TBLSinhvien theo định dạng XML using System; using System.Collections.Generic; using System.ComponentModel; using System.Xml; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Text; using System.Windows.Forms; namespace ExecuteXmlReader { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnXmlReader_Click(object sender, EventArgs e) { SqlConnection conn = new SqlConnection(); string connectionString = @"server =(local)\SQLEXPRESS ;" + "database = Sinhvien;" + "Integrated Security = true;"; conn.ConnectionString = connectionString; try { // Mở kết nối cơ sở dữ liệu conn.Open(); // Khai báo và khởi tạo đối tượng SqlCommand SqlCommand cmd = new SqlCommand("Select top 1 * from TBLSinhvien for xml auto", conn); //Khai báo đối tượng XmlReader XmlReader xmlrd = cmd.ExecuteXmlReader(); XmlDocument doc = new XmlDocument(); doc.Load(xmlrd); string str = ""; //Đọc từng bản ghi foreach (XmlNode xmlNode in doc.ChildNodes) { str += xmlNode.OuterXml +"\n"; } xmlrd.Close(); MessageBox.Show(str); //Đóng và giải phóng kết nối cơ sở dữ liệu conn.Close(); conn.Dispose(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } } } Kết quả : 2.5 Xây dựng lớp dùng chung cho SQLServer Khi chúng ta muốn sử dụng các phương thức trên chung trong cơ sở dữ liệu SQL Server ,để có thể truyền vào tham số thì chúng ta sẽ xây dụng lớp dùng chung , giả sử là Database và kêt hợp với đôí tượng SqlConnection ở phần trên . Ta xét ví dụ sau  Ví dụ : [...]... prm = new SqlParameter(); // Khai báo các thuộc tính ứng với tên tham số // Tham số Masv prm.ParameterName = "@Masv"; prm.SqlValue = "SV0000015"; prm.SqlDbType = SqlDbType.NChar; prm.Size = 10; // Thêm dữ liệu SqlParameter vào đối tượng //SqlCommand cmd.Parameters.Add(prm); // Khai báo và khởi tạo đối tượng Sqlparameter // với hai tham số prm = new SqlParameter("@Hoten", "Vũ Thị Thảo"); prm.SqlDbType... prm = new SqlParameter(); // Khai báo các thuộc tính ứng với tên tham số // Tham số Masv prm.ParameterName = "@Masv"; prm.SqlValue = "SV0000016"; prm.SqlDbType = SqlDbType.NChar; prm.Size = 10; // Thêm dữ liệu SqlParameter vào đối tượng // SqlCommand cmd.Parameters.Add(prm); // Khai báo và khởi tạo đối tượng Sqlparameter // với hai tham số prm = new SqlParameter("@Hoten", "Nguyễn Xuân Phương"); prm.SqlDbType . Lập trình cơ sở dữ liệu I. Đối tượng Sqlconnection Không gian tên sử dụng là : System.Data.SqlClient ; 1 tương tự như phương thức ExecuteReader nhưng nó trả về tập dữ liệu có định dạng XML và sử dụng đối tượng XMLReader để nắm dữ tập dữ liệu đó.  Ví dụ : Đọc bản ghi đầu tiên trong bảng TBLSinhvien. sqlCommand.ExecuteNonQuery(); // Đóng kết nối sqlConnection.Close(); // Giải phóng kêt nối cơ sở dữ liệu sqlConnection.Dispose(); MessageBox.Show("Đã cập nhật " + i.ToString() + "

Ngày đăng: 02/07/2014, 18:20

Tài liệu cùng người dùng

Tài liệu liên quan