1. Trang chủ
  2. » Kỹ Thuật - Công Nghệ

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

18 331 0
Tài liệu đã được kiểm tra trùng lặp

Đ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

Thông tin cơ bản

Định dạng
Số trang 18
Dung lượng 246 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Đối tượng Sqlconnection Không gian tên sử dụng là : System.Data.SqlClient ; 1.. 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

Trang 1

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"/>

Trang 2

</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();

Trang 3

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

Trang 4

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)

Trang 5

{

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();

Trang 6

}

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ả :

Trang 7

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) {

Trang 8

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 ả :

Trang 9

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);

Trang 10

//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ụ :

Trang 11

using System;

using System.Data;

using System.Data.SqlClient;

using System.Drawing;

using System.Windows.Forms;

namespace Lopdungchung

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

}

private void Form1_Load(object sender, EventArgs e)

{

Connection cn = new Connection();

}

private void btnENQ_Click(object sender, EventArgs e)

{

Database sql = new Database();

try

{

int r = sql.ExecuteNonQuery("Update TBLSinhvien set

Matinh='T02' where Masv = 'SV0000010'", CommandType.Text);

MessageBox.Show("Đã có " + r.ToString() + " bản ghi

đã được sửa");

}

catch (Exception ex)

{

MessageBox.Show(ex.Message + sql.StrError);

}

}

private void btnESL_Click(object sender, EventArgs e)

{

Database sql = new Database();

try

{

object obj = sql.ExecuteScalar("Select count(*) from

TBLSinhvien", CommandType.Text); MessageBox.Show("Có " + Convert.ToString(obj) + "

bản ghi trong bảng TBLSinhvien"); }

catch (Exception ex)

{

MessageBox.Show(ex.Message + sql.StrError);

}

}

private void btnER_Click(object sender, EventArgs e)

{

Database sql = new Database();

try

{

object[] obj = sql.ExcuteReader("Select * from

TBLSinhvien where MaSV = 'SV0000004'", CommandType.Text);

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

TỪ KHÓA LIÊN QUAN

w