java database connectivity tiếng việt

39 288 0
java database connectivity tiếng việt

Đ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

Java DataBase Connectivity_ JDBC Tài liệu tham khảo: http://java.sun.com/docs/books/tutorial/jdbc/basics/index.html http://java.sun.com/docs/books/tutorial/jdbc/jdbc2dot0/index.html Nội dung học † † † † † Tìm hiểu JDBC API JDBC Drivers Mơ hình 2-tier 3-tier Các bước truy xuất CSDL dùng JDBC Các ví dụ minh hoạ Transactions Sau học này, sinh viên viết chương trình truy xuất CSDL ngơn ngữ Java JDBC API † JDBC API viết tắt Java Database Connectivity Application Programming Interface † Cung cấp lớp interface để hổ trợ Java program truy xuất database JDBC Drivers † Giúp cho ứng dụng truy xuất CSDL theo chuẩn chung khơng phục thuộc vào DBMS † JDBC Driver nhận requests từ client, converts sang dạng mà Database hiểu được. Ngược lại, JDBC Driver nhận response, dịch sang Java data format, để client application hiểu -> Java-to-SQL translator java.sql package † Chứa interfaces classes định nghĩa JDBC API để access database † Các Interfaces java.sql package: „ „ „ „ CallableStatement Connection DatabaseMetaData Driver „ „ „ „ PreparedStatement ResultSet ResultSetMetaData Statement Các exception : DataTruncation, SQLException SQLWarning JDBC Drivers † JDBC driver thích hợp với mơ hình client/server † Có loại JDBC drivers: „ JDBC-ODBC Bridge „ Native API Java „ JDBC Network „ Native Protocol JDBC-ODBC Bridge † Được hổ trợ JavaSoft. † Dùng cho nhiều databases. † Sử dụng dịch vụ DataSource ODBC Native-API-Partly-Java Driver † Sử dụng local native libraries để trao đổi với database cách dùng CLI (Call Level Interface) † Khi client gởi request, driver dịch JDBC request sang native method call chuyển request cho native CLI JDBC-Net-All-Java Driver † Khác với drivers trước vị trí native database access libraries † Native CLI libraries đặt remote server driver dùng network protocol cho việc trao đổi application driver † Driver chia thành phần: phần chứa tất phần Java mà download cho client phần server chứa hai Java native methods Native-Protocol-All-Java Driver † 100% Java khơng dùng CLI libraries † Có khả trao đổi với database cách trực tiếp mà khơng cần translation 10 Viết chương trình để insert record cho table departments try { Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); String url =“jdbc:odbc:data” ; Connection cn = DriverManager.getConnection(url); Statement st = cn.createStatement(); String sql = “insert into departments (depID, depName) values (‘ns’, ‘phòng nhân ‘)“; st.executeUpdate(sql); st.close(); cn.close(); }catch(Exception e){} } // main } //class 24 Interface ResultSet † Được tạo từ phương thức executeQuery() đối tượng Statement, PreparedStatement, CallableStatement † Chứa liệu trả từ lệnh select query † chứa cursor đến record hành. Khi resultset vừa tạo ra, cursor đến before the first record † Dùng phương thức next() để di chuyển cursor đến record kế tiếp, đến after the last record trả giá trị false † Default, ResultSet readOnly forward only 25 Các phương thức thường dùng (1) boolean first() Moves the cursor to the first row in this ResultSet object. boolean getBoolean(int columnIndex) Retrieves the value of the designated column in the current row of this ResultSet object as a boolean in the Java programming language. boolean getBoolean(String columnName) Retrieves the value of the designated column in the current row of this ResultSet object as a boolean in the Java programming language. byte getByte(int columnIndex) Retrieves the value of the designated column in the current row of this ResultSet object as a byte in the Java programming language. byte getByte(String columnName) Retrieves the value of the designated column in the current row of this ResultSet object as a byte in the Java programming language. 26 Các phương thức thường dùng (2) Date getDate(int columnIndex) Retrieves the value of the designated column in the current row of this ResultSet object as a java.sql.Date object in the Java programming language. Date getDate(String columnName) Retrieves the value of the designated column in the current row of this ResultSet object as a java.sql.Date object in the Java programming language. double getDouble(int columnIndex) Retrieves the value of the designated column in the current row of this ResultSet object as a double in the Java programming language. double ge tDouble(String columnName) Retrieves the value of the designated column in the current row of this ResultSet object as a double in the Java programming language. 27 Các phương thức thường dùng (3) float getFloat(int columnIndex): Retrieves the value of the designated column in the current row of this ResultSet object as a float in the Java programming language. float getFloat(String columnName): Retrieves the value of the designated column in the current row of this ResultSet object as a float in the Java programming language. int getInt(int columnIndex): Retrieves the value of the designated column in the current row of this ResultSet object as an int in the Java programming language. int getInt(String columnName): Retrieves the value of the designated column in the current row of this ResultSet object as an int in the Java programming language. long getLong(int columnIndex): Retrieves the value of the designated column in the current row of this ResultSet object as a long in the Java programming language. long getLong(String columnName):Retrieves the value of the designated column in the current row of this ResultSet object as a long in the Java programming 28 Các phương thức thường dùng (4) ResultSetMetaData getMetaData(): Retrieves the number, types and properties of this ResultSet object's columns. String getString(int columnIndex): Retrieves the value of the designated column in the current row of this ResultSet object as a String in the Java programming language. String getString(String columnName): Retrieves the value of the designated column in the current row of this ResultSet object as a String in the Java programming language. boolean last(): Moves the cursor to the last row in this ResultSet object. boolean next():Moves the cursor down one row from its current position. boolean previous():Moves the cursor to the previous row in this ResultSet object. 29 Viết chương trình liệt kê record table departments Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); String url =“jdbc:odbc:data” ; Connection cn = DriverManager.getConnection(url); Statement st = cn.createStatement(); String sql = “select * from departments “; ResultSet rs = st.executeQuery(sql); while (rs.next()) { System.out.println(“ DepID : “ + rs.getString(“depid”)); System.out.println(“DepName : “ + rs.getString(“depName”)); } st.close(); cn.close(); 30 Interface ResultSetMetaData † Cung cấp methods dùng để lấy thơng tin đối tượng ResultSet. int getColumnCount():Returns the number of columns in this ResultSet String getColumnLabel(int column) : Gets the designated column's suggested title for use in printouts and displays. String getColumnName(int column): Get the designated column's name. int getColumnType(int column): Retrieves the designated column's SQL type. String getColumnTypeName(int column) : Retrieves the designated column's database-specific type name. String getTableName(int column): Gets the designated column's table name. 31 Ví dụ dùng ResultSetMetadata Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection cn = DriverManager.getConnection("jdbc:odbc:data"); Statement st = cn.createStatement(); String sqlstr= "select * from departments"; ResultSet rs =st.executeQuery(sqlstr); ResultSetMetaData rsmd = rs.getMetaData(); while (rs.next()) { for (int i=1;i dùng transaction † Khi connection sau tạo chế độ Auto commit bật lên. † Muốn tạo transaction, ta phải tắt chế độ này: con.setAutoCommit(false); † Nếu lệnh transaction thực thành cơng gọi phương thức commit connection † Nếu có lệnh transaction khơng thực được, dùng phương thức rollback để rollback transaction 38 ví dụ transaction try{ con.setAutoCommit(false); // bắt đầu transaction PreparedStatement updateSales = con.prepareStatement( "UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?"); updateSales.setInt(1, 50); updateSales.setString(2, "Colombian"); updateSales.executeUpdate(); PreparedStatement updateTotal = con.prepareStatement( "UPDATE COFFEES SET TOTAL = TOTAL + ? WHERE COF_NAME LIKE ?"); updateTotal.setInt(1, 50); updateTotal.setString(2, "Colombian"); updateTotal.executeUpdate(); con.commit(); // kết thúc transaction thành cơng con.setAutoCommit(true); }catch( Exception e){ con.rollback(); } 39 [...]... cho database server -> proxy Ưu: Tách database server ra khỏi server application Dễ nâng cấp 14 CÁC BƯỚC CSDL 1 2 3 4 5 6 7 TRUY XUẤT Import java. sql package Load và đăng ký driver Thiết lập connection đến database server Tạo đối tượng statement: Statement/PreparedStat ement/CallableStatemen t Thực hiện lệnh SQL Nhận kết quả trả về và xử lý Đóng statement và connection 15 Thiết lập connection đến database. .. the Java programming language 26 Các phương thức thường dùng (2) Date getDate(int columnIndex) Retrieves the value of the designated column in the current row of this ResultSet object as a java. sql.Date object in the Java programming language Date getDate(String columnName) Retrieves the value of the designated column in the current row of this ResultSet object as a java. sql.Date object in the Java. .. commit database Statement createStatement(): Creates a Statement object for sending SQL statements to the database Statement createStatement(int resultSetType, int resultSetConcurrency) Creates a Statement object that will generate ResultSet objects with the given type and concurrency 17 Interface Connection (2) CallableStatement prepareCall(String sql) Creates a CallableStatement object for calling database. .. JDBC-ODBC driver 1 Tạo file HRManagement.mdb • 2 Thiết lập Data source ODBC với data source name (DSN) là DATA (không bắt buộc phải trùng tên file mdb) •3 Viết chương trình Java để thực hiện truy xuất CSDL 21 Chương trình mã nguồn Java Import java. sql.*; public class TaoTable1 { public static void main(String[] args) { try { Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); //load driver Connection cn = DriverManager.getConnection(“jdbc:odbc:data”);... ResultSet object as a boolean in the Java programming language boolean getBoolean(String columnName) Retrieves the value of the designated column in the current row of this ResultSet object as a boolean in the Java programming language byte getByte(int columnIndex) Retrieves the value of the designated column in the current row of this ResultSet object as a byte in the Java programming language byte getByte(String... statement và connection 15 Thiết lập connection đến database Lớp java. sql.DriverManager cung cấp các phương thức để load drivers: static Connection getConnection(String url) Attempts to establish a connection to the given database URL static Connection getConnection(String url, Properties info) Attempts to establish a connection to the given database URL static Connection getConnection(String url, String... double in the Java programming language double ge tDouble(String columnName) Retrieves the value of the designated column in the current row of this ResultSet object as a double in the Java programming language 27 Các phương thức thường dùng (3) float getFloat(int columnIndex): Retrieves the value of the designated column in the current row of this ResultSet object as a float in the Java programming... this ResultSet object as a float in the Java programming language int getInt(int columnIndex): Retrieves the value of the designated column in the current row of this ResultSet object as an int in the Java programming language int getInt(String columnName): Retrieves the value of the designated column in the current row of this ResultSet object as an int in the Java programming language long getLong(int... sending parameterized SQL statements to the database PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) Creates a PreparedStatement object that will generate ResultSet objects with the given type and concurrency 18 Interface Connection (3) void rollback() Undoes all changes made in the current transaction and releases any database locks currently held by this Connection... a connection to the given database URL static Driver getDriver(String url) Attempts to locate a driver that understands the given URL 16 Interface Connection (1) Mơ tả một kết nối với một CSDL cụ thể Đối tượng Connection có thể cung cấp các thơng tin mơ tả về các tables, các SQL grammar được hổ trợ, các stored procedures, … bằng phương thức getMetaData để trả về đối tượng DatabaseMetaData void close(): . ngôn ngữ Java 3 JDBC API  JDBC API viếttắtcủa Java Database Connectivity Application Programming Interface  Cung cấpcáclớpvàcác interface để hổ trợ Java program có thể truy xuất database 4 JDBC. 1 Java DataBase Connectivity_ JDBC Tài liệuthamkhảo: http:/ /java. sun.com/docs/books/tutorial/jdbc/basics/index.html http:/ /java. sun.com/docs/books/tutorial/jdbc/jdbc2dot0/index.html 2 Nộidung. phầnJava màcóthể download về cho client và phầnserver chứacả hai Java và native methods 10 Native-Protocol-All -Java Driver  100% Java và không dùng CLI libraries  Có khả năng trao đổivới database

Ngày đăng: 14/09/2015, 11:14

Mục lục

  • Nội dung bài học

  • Two-Tier Client Server Model

  • Three-Tier Client Server Model

  • CÁC BƯỚC TRUY XUẤT CSDL

  • Thiết lập connection đến database

  • Các phương thức thường dùng (1)

  • Các phương thức thường dùng (2)

  • Các phương thức thường dùng (3)

  • Các phương thức thường dùng (4)

  • Ví dụ dùng ResultSetMetadata

  • Ví dụ gọi thực hiện một stored procedure có tham số truyền vào

  • Ví dụ thực hiện một stored procedure có tham số trả giá trị về

  • ví dụ về transaction

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

  • Đang cập nhật ...

Tài liệu liên quan