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>;
+ 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
{
// 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");
}
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)
{
}
}
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
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)
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()
//Đó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ụ :
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();
}
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);
MessageBox.Show("Thông tin về SV có mà SV0000004 : "
+ Convert.ToString(obj[1]) + " - " +
Convert.ToString(obj[2]));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + sql.StrError);
}
}
}
public class Connection
{
public static SqlConnection conn;
static Connection()
{
conn = new SqlConnection();
conn.ConnectionString = @"server = QUYETNV87\SQLEXPRESS ;"
recordNumbers = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
strError = "Error : " + ex.Message;
}
return recordNumbers;
}
public object ExecuteScalar(String strSQL, CommandType
cmdType)
{
object objValues = null;
// Khai báo và khởi tạo đối tượng SqlCommand
SqlCommand cmd = new SqlCommand();
cmd.CommandText = strSQL;
cmd.CommandType = cmdType;
cmd.Connection = Connection.conn;
try
{
objValues = cmd.ExecuteScalar();
}
catch (Exception ex)
{
strError = "Error : " + ex.Message;
}
return objValues;
}
public object[] ExcuteReader(String strSQL, CommandType
cmdType)
{
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace DoituongSqlParameter
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnText_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = @"server =
(local)\SQLEXPRESS;"
+ "database = Sinhvien;"
+ "Integrated Security =
true;";
try
{
conn.Open();
// Khai báo và khởi tạo đối tượng SqlCommand
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "insert into
TBLSinhvien(Masv,Hoten,Gioitinh,Ngaysinh,M
atinh,Malop,Chucvu,Email,Dienthoai)"
+
prm.SqlValue = "11/10/1987";
cmd.Parameters.Add(prm);
// Khai báo và khởi tạo đối tượng SqlParameter
// với 3 tham số
prm = new SqlParameter("@Matinh",
SqlDbType.NChar, 3);
prm.SqlValue = "T17";
cmd.Parameters.Add(prm);
// Khai báo và khởi tạo đối tượng SqlParameter
// với 3 tham số
prm = new SqlParameter("@Malop",
SqlDbType.NChar, 10);
prm.SqlValue = "1900052";
cmd.Parameters.Add(prm);
// Khai báo và khởi tạo đối tượng SqlParameter
// với 3 tham số
prm = new SqlParameter("@Chucvu",
SqlDbType.NVarChar, 20);
prm.SqlValue = "";
cmd.Parameters.Add(prm);
prm = new SqlParameter("@Email",
SqlDbType.NChar, 30);
prm.SqlValue = "[email protected]";
cmd.Parameters.Add(prm);
// Khai báo và khởi tạo đối tượng SqlParameter
// với 3 tham số
prm = new SqlParameter("@Dienthoai",
SqlDbType.NChar, 10);
prm.SqlValue = "0975775775";
cmd.CommandType = CommandType.StoredProcedure;
// Khai báo và khởi tạo đối tượng SqlParameter
SqlParameter 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 = SqlDbType.NVarChar;
prm.Size = 50;
cmd.Parameters.Add(prm);
// Khai báo và khởi tạo đối tượng SqlParameter
// với 3 tham số
prm = new SqlParameter("@Gioitinh",
SqlDbType.NChar, 10);
prm.SqlValue = "Nam";
cmd.Parameters.Add(prm);
// Khai báo và khởi tạo đối tượng SqlParameter
// ứng với ts Ngaysinh
prm = new SqlParameter("@Ngaysinh",
SqlDbType.DateTime);
prm.SqlValue = "10/25/1986";
cmd.Parameters.Add(prm);
// Khai báo thuộc tính Connection
cmd.Connection = conn;
cmd.ExecuteNonQuery();
conn.Close();
conn.Dispose();
MessageBox.Show("Đã chèn thêm bản ghi thành
công\nbằng việc sử dụng đối
tượng\nSqlParameter với thủ
tục ");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
Kết quả :