Lập trình Java - Kết nối CSDL với Java

Java Database Connectivity (JDBC) là tập API chuẩn dùng để kết nối giữa ngôn ngữ lập trình Java với nhiều loại cơ sở dữ liệu (Database – DB) khác nhau.

JDBC cung cấp các hàm thực hiện các công việc liên quan đến DB như:

Tạo kết nối đến DB

Chạy các câu lệnh SQL

Thực thi các câu truy vấn

Hiện thị và sửa đổi các dòng dữ liệu (records)

 

 

pptx27 trang | Chuyên mục: Java | Chia sẻ: dkS00TYs | Lượt xem: 7790 | Lượt tải: 1download
Tóm tắt nội dung Lập trình Java - Kết nối CSDL với Java, để xem tài liệu hoàn chỉnh bạn click vào nút "TẢI VỀ" ở trên
Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 3/24/2014 SGU - CNTT - Lập Trình JAVA ‹#› Kết nối CSDL với JAVA ThS. Hoàng Mạnh Hà hoangha84@gmail.com https://sites.google.com/site/hoangha84 Nội dung SGU - CNTT - Lập Trình JAVA 2 Java Database Connectivity JDBC Driver Types Hiện thị dữ liệu với JTable từ ResultSet Java Database Connectivity SGU - CNTT - Lập Trình JAVA 3 Giới thiệu SGU - CNTT - Lập Trình JAVA 4 Java Database Connectivity (JDBC) là tập API chuẩn dùng để kết nối giữa ngôn ngữ lập trình Java với nhiều loại cơ sở dữ liệu (Database – DB) khác nhau. JDBC cung cấp các hàm thực hiện các công việc liên quan đến DB như: Tạo kết nối đến DB Chạy các câu lệnh SQL Thực thi các câu truy vấn Hiện thị và sửa đổi các dòng dữ liệu (records) Kiến trúc JDBC SGU - CNTT - Lập Trình JAVA 5 JDBC API JDBC Driver API Các thành phần phổ biến trong JDBC SGU - CNTT - Lập Trình JAVA 6 DriverManager: lớp chứa danh sách các DB driver. Driver: xử lý các giao tiếp với DB server. Thông thường ít dùng trực tiếp mà thông qua DriverManager. Connection: gồm các hàm thao tác với DB, các thao tác với DB thông qua đối tượng connection. Statement: đối tượng để gửi các SQL statements đến DB, có thể có các tham số để thực thi stored procedure ResultSet: đối tượng dùng để lưu dữ liệu trả về từ DB sau khi thực thi một câu SQL bằng đối tượng Statement. SQLException: xử lý các lỗi xảy ra trong ứng dụng. JDBC driver SGU - CNTT - Lập Trình JAVA 7 MySQL JDBC driver: MySQL Connector/J  Microsoft SQL Server:  PostgreSQL DB, Oracle DB: JDBC driver được cài sẵn trong quá trình cài đặt chương trình. Sau khi download, trong Project của NetBeans: Click phải Libraries  Add JAR/Folder… Chỉ đến file .jar tương ứng. VD: sqljdbc4.jar Các bước xây dựng ứng dụng JDBC SGU - CNTT - Lập Trình JAVA 8 Import the packages: thêm vào các gói chứa những lớp JDBC liên quan, thường thì chỉ cần import java.sql.* là được. Register the JDBC driver: khởi tạo một driver để có thể mở kết nối với DB. Open a connection: sử dụng phương thức DriverManager.getConnection() để tạo một đối tượng Connection đại diện cho kết nối vật lý với DB Execute a query: sử dụng đối tượng Statement. Extract data from result set: Sử dụng các hàm tương ứng ResultSet.getXXX() Clean up the environment Register the JDBC driver SGU - CNTT - Lập Trình JAVA 9 Các thông tin JDBC driver khác nhau với mỗi loại JDBC driver: MySQL: "com.mysql.jdbc.Driver" MS SQL Server: "com.microsoft.sqlserver.jdbc.SQLServerDriver " Để đăng kí JDBC driver ta dùng phương thức: Class.forName("Tên JDBC driver") Open a connection SGU - CNTT - Lập Trình JAVA 10 Thông qua đối tượng của lớp Connection và phương thức getConnection() của lớp DriverManager: Connection conn = DriverManager.getConnection(DB_URL, USER, PASS); Trong đó: DB_URL: MS SQL Server: “jdbc:sqlserver://SERVERNAME:PORT;databaseName=DBNAME” MySQL: "jdbc:mysql://SERVERNAME:PORT/DBNAME" USER: tên đăng nhập DB PASS: mật khẩu đăng nhập DB SERVERNAME: trong Server name khi đăng nhập SQL Server. PORT: trong properties/IP Addresses của TCP/IP khi mở SQL Server Configuration Manager. Execute a query SGU - CNTT - Lập Trình JAVA 11 Tạo đối tượng Statement bằng phương thức createStatement() của đối tượng Connection: Statement stmt = conn.createStatement(); Sau đó chạy câu lệnh sql bằng phương thức executeQuery(“Câu lệnh sql”) và lấy giá trị trả về bằng đối tượng ResultSet: ResultSet rs = stmt.executeQuery(sql); Extract data from result set SGU - CNTT - Lập Trình JAVA 12 Bằng cách sử dụng các phương thức của đối tượng của lớp ResultSet rs.next(): duyệt dòng kế tiếp của rs, trả về true nếu có, false nếu không có dòng dữ liệu. Các phương thức getXXX(“Tên cột”) rs.getInt() rs.getString() Clean-up environment SGU - CNTT - Lập Trình JAVA 13 Sử dụng các phương thức close() để hủy các đối tượng: ResultSet: rs.close(); Statement: stmt.close(); Connection: conn.close(); JDBC Driver Types  SGU - CNTT - Lập Trình JAVA 14 Type 1: JDBC-ODBC Bridge Driver SGU - CNTT - Lập Trình JAVA 15 In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client machine. Using ODBC requires configuring on your system a Data Source Name (DSN) that represents the target database. When Java first came out, this was a useful driver because most databases only supported ODBC access but now this type of driver is recommended only for experimental use or when no other alternative is available. Type 1: JDBC-ODBC Bridge Driver SGU - CNTT - Lập Trình JAVA 16 Type 2: JDBC-Native API SGU - CNTT - Lập Trình JAVA 17 In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls which are unique to the database. These drivers typically provided by the database vendors and used in the same manner as the JDBC-ODBC Bridge, the vendor-specific driver must be installed on each client machine. If we change the Database we have to change the native API as it is specific to a database and they are mostly obsolete now but you may realize some speed increase with a Type 2 driver, because it eliminates ODBC's overhead. Type 2: JDBC-Native API SGU - CNTT - Lập Trình JAVA 18 Type 3: JDBC-Net pure Java SGU - CNTT - Lập Trình JAVA 19 In a Type 3 driver, a three-tier approach is used to accessing databases. The JDBC clients use standard network sockets to communicate with an middleware application server. The socket information is then translated by the middleware application server into the call format required by the DBMS, and forwarded to the database server. This kind of driver is extremely flexible, since it requires no code installed on the client and a single driver can actually provide access to multiple databases. Type 3: JDBC-Net pure Java SGU - CNTT - Lập Trình JAVA 20 Type 4: 100% pure Java SGU - CNTT - Lập Trình JAVA 21 In a Type 4 driver, a pure Java-based driver that communicates directly with vendor's database through socket connection. This is the highest performance driver available for the database and is usually provided by the vendor itself. This kind of driver is extremely flexible, you don't need to install special software on the client or server. Further, these drivers can be downloaded dynamically. Type 4: 100% pure Java SGU - CNTT - Lập Trình JAVA 22 Which Driver should be used? SGU - CNTT - Lập Trình JAVA 23 If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred driver type is 4. If your Java application is accessing multiple types of databases at the same time, type 3 is the preferred driver. Type 2 drivers are useful in situations where a type 3 or type 4 driver is not available yet for your database. The type 1 driver is not considered a deployment-level driver and is typically used for development and testing purposes only. Hiện thị dữ liệu với JTable từ ResultSet SGU - CNTT - Lập Trình JAVA 24 Nguyên tắc cơ bản SGU - CNTT - Lập Trình JAVA 25 JTable hiện thị nội dung theo một model. Mỗi model gồm 2 phần: Tên cột Các dòng nội dung TableModel là interface được xây dựng sẵn trong Java. Thông thường ta sử dụng thông qua lớp DefaultTableModel đã được thực thi interface. Các bước thực hiện SGU - CNTT - Lập Trình JAVA 26 Khai báo một đối tượng model thuộc lớp DefaultTableModel DefaultTableModel model = new DefaultTableModel(); Xây dựng tên cột cho model vừa tạo thông qua phương thức: model.setColumnIdentifiers(colName); Trong đó colName là một mảng object chứa tên các cột Các bước thực hiện SGU - CNTT - Lập Trình JAVA 27 Nếu muốn xây dựng tên cột theo đúng tên cột có trong ResultSet, ta phải dùng thông qua phương thức getColumnLabel() của đối tượng ResultSetMetaData: ResultSetMetaData metaPhongBan = rs.getMetaData(); String colName[] = new String[metaPhongBan.getColumnCount()]; for(int i = 0; i < colName.length; i++) { System.out.println(metaPhongBan.getColumnLabel(i+1)); colName[i] = metaPhongBan.getColumnLabel(i+1); } model.setColumnIdentifiers(colName); Các bước thực hiện SGU - CNTT - Lập Trình JAVA 28 Để xây dựng các dòng dữ liệu cho model, ta phải đưa từng dòng vào model như sau: while (rs.next()){ Object dataRow[] = new Object[colName.length]; for(int i = 0; i<dataRow.length;i++){ dataRow[i]=rs.getObject(i+1); } model.addRow(dataRow); } Sau đó dùng phương thức setModel() của JTable để chỉ định model cho JTable: tbPhongBan.setModel(model); 

File đính kèm:

  • pptxLập trình Java - Kết nối CSDL với Java.pptx
Tài liệu liên quan