Presentation is loading. Please wait.

Presentation is loading. Please wait.

מסדי נתונים תשס " ג 1 JDBC Java Database Connectivity קורס מסדי נתונים.

Similar presentations


Presentation on theme: "מסדי נתונים תשס " ג 1 JDBC Java Database Connectivity קורס מסדי נתונים."— Presentation transcript:

1 מסדי נתונים תשס " ג 1 JDBC Java Database Connectivity קורס מסדי נתונים

2 מסדי נתונים תשס " ג 2 שימוש ב -JDBC רוצים לאפשר לתוכניות לגשת לבסיס נתונים – על מנת להרחיב לייצר תוכנה שעובדת עם מסד הנתונים – על מנת להרחיב את יכולת שליפת המידע של מערכת מסד הנתונים לדוגמא, חישוב סגור טרנזיטיבי : עבור יחס E(source, target) המתאר צלעות בגרף מכוון, רוצים לדעת מהם כל הקדקודים שניתן להגיע אליהם מקודקוד נתון v

3 מסדי נתונים תשס " ג 3 שימוש בתקשורת TCP/IP java.net JDBC Network OS java.sql

4 מסדי נתונים תשס " ג 4 Changing the Java CLASSPATH You must add to.cshrc (or to your classpaths definitions file) the followings: setenv CLASSPATH ${CLASSPATH}: /usr/local/java/oracle/lib/classes12.zip: /usr/local/java/oracle/lib/classes111.zip setenv CLASSPATH ${CLASSPATH}: /usr/local/java/oracle/lib/classes12.zip: /usr/local/java/oracle/lib/classes111.zip

5 מסדי נתונים תשס " ג 5 JDBC Drivers JDBC Type I “Bridge” Type II “Native” Type III “Middleware” Type IV “Pure” ODBC Driver CLI (.lib) Middleware Server Java Socket

6 מסדי נתונים תשס " ג 6 שלבי עבודה Load the driver Define the Connection URL Establish the Connection Create a Statement object Execute a query Process the result Close the connection

7 מסדי נתונים תשס " ג 7 Important Classes DriverManager –loads, chooses drivers Driver –connects to actual database Connection –allows sending a series of SQL statements to and from the DB Statement –a single SQL statement ResultSet –the records returned from a Statement

8 מסדי נתונים תשס " ג 8 DriverManager Driver Connection Statement ResultSet

9 מסדי נתונים תשס " ג 9 The DriverManager The DriverManager tries all the drivers Uses the first one that works When a driver class is first loaded, it registers itself with the DriverManager Therefore, to load a driver, just register it!

10 מסדי נתונים תשס " ג 10 Loading the Driver Registering the driver directly and automatically: Class.forName( “oracle.jdbc.driver.OracleDriver"); Calling Class.forName, automatically –creates an instance of the driver –registers the driver with the DriverManager

11 מסדי נתונים תשס " ג 11 Another Option Another option is to create an instance of the driver and register it with the Driver Manager: Driver driver = new oracle.jdbc.OracleDriver(); DriverManager.registerDriver(driver);

12 מסדי נתונים תשס " ג 12 Creating a Connection Use getConnection on the Driver Connection getConnection (String url, String user, String password) Connects to given JDBC URL with given user name and password Throws java.sql.SQLException returns a Connection object

13 מסדי נתונים תשס " ג 13 URLS Gives the required information for making the connection to the database For example, Snoopy will use the URL jdbc:oracle:thin:snoopy/snoopy@sol4:152 1:stud Database urlUser name Password Host Port Database name

14 מסדי נתונים תשס " ג 14 Connection A Connection represents a session with a specific database Within the context of a Connection, SQL statements are executed and results are returned

15 מסדי נתונים תשס " ג 15 Connections There can be multiple connections to a database A connection provides “metadata”, i.e., information about the database, tables, and fields Connection object has methods to deal with transactions

16 מסדי נתונים תשס " ג 16 Creating a Connection String url = "jdbc:oracle:thin:snoopyo/snoopy@sol4:1521:stud"; try { DriverManager.registerDriver( new oracle.jdbc.OracleDriver()); Connection con = DriverManager.getConnection(url); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); }

17 מסדי נתונים תשס " ג 17 Creating a Connection String url = "jdbc:oracle:thin:snoopyo/snoopy@sol4:1521:stud"; try { Class.forName ( “ oracle.jdbc.OracleDriver"); Connection con = DriverManager.getConnection(url); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); }

18 מסדי נתונים תשס " ג 18 Statements Statement createStatement() –returns a new Statement object PreparedStatement prepareStatement(String sql) –returns a new PreparedStatement object CallableStatement prepareCall(String sql) –returns a new CallableStatement object Why all these different kinds of statements?

19 מסדי נתונים תשס " ג 19 Statements A Statement object is used for executing a static SQL statement and obtaining the results produced by it executeQuery is used for statements that return an output result executeUpdate is used for statements that need not return an output

20 מסדי נתונים תשס " ג 20 Executing Queries and Updates ResultSet executeQuery(String) –Execute a SQL statement that returns a single ResultSet int executeUpdate(String) –Execute a SQL INSERT, UPDATE or DELETE statement –Used for CREATE TABLE, DROP TABLE and ALTER TABLE –Returns the number of rows changed

21 מסדי נתונים תשס " ג 21 Cursor What is the result of a query? Is a remote connection different from a direct access to the database? How can a database send the result of a query through communication lines? The answer: using a cursor

22 מסדי נתונים תשס " ג 22 Cursor A mechanism to retrieve one tuple at a time from the database Supports –open (in declaration) –fetch (the next row) –move (to the first/next/previous row, forward, in most system also backward) –close

23 מסדי נתונים תשס " ג 23 Result Set A ResultSet provides access to a table of data generated by executing a Statement Only one ResultSet per Statement can be open at once The table rows are retrieved in sequence A ResultSet maintains a cursor pointing to its current row of data The 'next' method moves the cursor to the next row

24 מסדי נתונים תשס " ג 24 Working with ResultSet boolean next() –activates the next row –the first call to next() activates the first row –returns false if there are no more rows void close() –disposes of the ResultSet –allows you to re-use the Statement that created it –automatically called by most Statement methods

25 מסדי נתונים תשס " ג 25 Getting Values from Rows Type getType(int columnIndex) –returns the given field as the given type –fields indexed starting at 1 (not 0) Type getType(String columnName) –same, but uses name of field –less efficient int findColumn(String columnName) –looks up column index given column name

26 מסדי נתונים תשס " ג 26

27 מסדי נתונים תשס " ג 27 Example Code Example

28 מסדי נתונים תשס " ג 28 Optimized Statements Prepared Statements –SQL calls that you make again and again –allows driver to optimize (compile) queries –created with Connection.prepareStatement() Stored Procedures –written in DB-specific language –stored inside database –accesed with Connection.prepareCall()

29 מסדי נתונים תשס " ג 29 Querying with PreparedStatement String queryStr = "SELECT * FROM Cars " + "WHERE Company = ? and Cost < ?”; PreparedStatement pstmt = con.prepareStatement(queryStr); pstmt.setString(1, “Ford”); pstmt.setInt(2, 100000); ResultSet rs = pstmt.executeQuery();

30 מסדי נתונים תשס " ג 30 Changing DB with PreparedStatement String deleteStr = “DELETE FROM Cars " + "WHERE Company = ? and Cost < ?”; PreparedStatement pstmt = con.prepareStatement(deleteStr); pstmt.setString(1, “Fiat”); pstmt.setInt(2, 10000); int delnum = pstmt.executeUpdate();

31 מסדי נתונים תשס " ג 31 Metadata Connection: –DatabaseMetaData getMetaData() ResultSet: –ResultSetMetaData getMetaData()

32 מסדי נתונים תשס " ג 32 Consider the case where you want to print the result Useful Methods of Metadata getColumnCount getColumnDisplaySize getColumnName getColumnType isNullabale

33 מסדי נתונים תשס " ג 33 Printing Query Output: Result Set (1) ResultSetMetaData rsmd = rs.getMetaData(); int numcols = rsmd.getColumnCount(); for (int i = 1 ; i <= numcols; i++) { if (i > 1) System.out.print(","); System.out.print(rsmd.getColumnLabel(i)); } Print Column Headers:

34 מסדי נתונים תשס " ג 34 Printing Query Output: Result Set (2) while (rs.next()) { for (int i = 1 ; i <= numcols; i++) { if (i > 1) System.out.print(","); System.out.print(rs.getString(i)); } System.out.println(""); } To get the data in the i-th column: rs.getString(i) To get the data in column A: rs.getString(“A”)

35 מסדי נתונים תשס " ג 35

36 מסדי נתונים תשס " ג 36 Example Code Example

37 מסדי נתונים תשס " ג 37 Transaction Management Transactions are not explicitly opened and closed Instead, the connection has a state called AutoCommit mode if AutoCommit is true, then every statement is automatically committed default case: true

38 מסדי נתונים תשס " ג 38 AutoCommit Connection.setAutoCommit(boolean) if AutoCommit is false, then every statement is added to an ongoing transaction you must explicitly commit or rollback the transaction using Connection.commit() and Connection.rollback()

39 מסדי נתונים תשס " ג 39 Timeout Use setQueryTimeOut to set a timeout for the driver to wait for a statement to be completed If the operation is not completed in the given time, an SQLException is thrown What is it good for?

40 מסדי נתונים תשס " ג 40 Connection Manager For a large threaded database server, create a Connection Manager object It is responsible for maintaining a certain number of open connections to the database When your applications need a connection, they ask for one from the CM’s pool Why? Because opening and closing connections takes a long time Warning: the CM should always setAutoCommit(false) when a connection is returned (why?)

41 מסדי נתונים תשס " ג 41 More Optimization You can execute a batch of commands, for example, a series of insertions to the database Depends on the driver support –addBatch(String sql) –executeBatch()


Download ppt "מסדי נתונים תשס " ג 1 JDBC Java Database Connectivity קורס מסדי נתונים."

Similar presentations


Ads by Google