Thursday, July 17, 2014

Căn bản về JDBC – Từng bước kết nối dữ liệu SQL server

  1. Đăng ký Driver.
  2. Thiết lập kết nối với DataBase Server.
  3. Tạo và thực thi câu lệnh.
  4. Xử lý kết quả và đóng kết nối.

Để đăng ký JDBC drive chúng ta sử dụng hàm forName của lớp Class

Đối với odbc:

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Cần đăng ký odbc user với hệ điều hành windows (tôi sẽ demo trực tiếp)

http://youtu.be/iRBQm1YrSHY

Đối với jdbc:

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

Cần nhúng thư viện jdbc của sql server vào ứng dụng. download tại jdbc sqlserver driver (phần nhúng vào tôi sẽ demo trực tiếp)

http://youtu.be/cRyPUvkZx-U

Tiếp theo, chúng ta thiết lập kết nối.

Đối với loại kết nối thứ 4 cho sql server

Connection conn = DriverManager.getConnection("jdbc:sqlserver://localhost;user=sa;password=sa;database=Northwind;");

Đối với loại kết nối thứ 1

Connection con = DriverManager.getConnection("jdbc:odbc:demo", "sa","sa");

Bước kế tiếp chúng ta tạo câu lệnh đọc dữ liệu và đón nhận thông qua ResultSet

Với odbc

Statement command = con.createStatement();
ResultSet result = command.executeQuery("Select * from Employees");

Với jdbc loại 4

PreparedStatement command = conn.prepareStatement("Select * from Employees where employeeid like ?");
command.setInt(1,id);
ResultSet result = command.executeQuery();

Đoạn trên chúng ta sử dụng dấu ? để tham qui định tham số trong câu lệnh truy vấn, sử dụng các setXXX(số thứ tự tham số bắt đầu = 1) với XXX là loại dữ liệu mối gán vào.

Thao tác cuối cùng là xử lý dữ liệu đã nhận về và đóng kết nối với database server. Trong phần này chúng ta chỉ đơn giản là liệt kê các cột dữ liệu gồm: tên cột, loại dữ liệu và ràng buộc của cột dữ liệu, hiển thị toàn bộ dữ liệu đã nhận được.

1. Thể hiện cấu trúc dữ liệu lấy về (giống nhau cho cả hai loại driver mà chúng ta đã thực hiện lý do là dữ liệu đã lấy về ứng dụng đề được chứa trong ResultSet

ResultSetMetaData rsm = result.getMetaData();

int count = rsm.getColumnCount();
  for(int i=0; i<count;i++) {
     System.out.print("Col " + rsm.getColumnName(i+1));
     System.out.println("is"+rsm.getColumnTypeName(i+1));
}

Chạy thử ứng dụng chúng ta có kết quả như sau:

Col EmployeeID is int identity
Col LastName is nvarchar
Col FirstName is nvarchar
Col Title is nvarchar
Col TitleOfCourtesy is nvarchar
Col BirthDate is datetime
Col HireDate is datetime
Col Address is nvarchar
Col City is nvarchar
Col Region is nvarchar
Col PostalCode is nvarchar
Col Country is nvarchar
Col HomePhone is nvarchar
Col Extension is nvarchar
Col Photo is image
Col Notes is ntext
Col ReportsTo is int
Col PhotoPath is nvarchar
Col Image is nvarchar
Col Hinh is varchar
Col Gender is bit

2. Duyệt và in kết quả ra màn hình

for (int i = 0; i < count; i++) {
  System.out.print("Col"+rsm.getColumnName(i+1) + "\t");
}
System.out.println();
while (result.next()) {
  for (int i = 0; i < count; i++) {
   System.out.print("Col"+result.getString(i + 1)+ "\t");
  }
  System.out.println("");
}

Chạy ứng dụng chúng ta có kết quả sau:

EmployeeID    LastName    FirstName    Title    TitleOfCourtesy   
1    Ngo Tuong Dan    Ngo    null    Ms.   
2    Fuller    Andrew    Vice President, Sales    Dr.   
3    Leverling    Janet    null    Ms.   
4    Peacock    Margaret    Sales Representative    Mrs.   
5    Buchanan    Steven    Sales Manager    Mr.   
6    Suyama    Michael    Sales Representative    Mr.   
7    King    Robert    Sales Representative    Mr.   
8    Callahan    Lauradddd    Inside Sales Coordinator    Ms.

Cuối cùng là đóng kết nối với database server

con.close();

Như vậy là chúng ta đã thực hiện được những thao tác rất rất cơ bản trong sử dụng jdbc để đọc dữ liệu.

>>>> Bài tiếp theo tôi sẽ thực hiện gọi hàm và thủ tục.

No comments:

Post a Comment

Translate