1 / 29

Basic JDBC

Basic JDBC. Celsina Bignoli bignolic@smccd.net. What is JDBC. Industry standard for database-connectivity between the Java language and a wide range of databases Generic Leverage existing database APIs Simple. JDBC Architecture. Java Application. DriverManager. Sybase Driver.

conner
Download Presentation

Basic JDBC

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Basic JDBC Celsina Bignoli bignolic@smccd.net

  2. What is JDBC • Industry standard for database-connectivity between the Java language and a wide range of databases • Generic • Leverage existing database APIs • Simple

  3. JDBC Architecture Java Application DriverManager Sybase Driver MySQL Driver Oracle Driver Sybase DB MySQL DB Oracle DB

  4. JDBC Drivers • Vendor-specific implementation of the JDBC interfaces • Transparent to the database application developers

  5. JDBC specifications JDBC 2.0 Specification JDBC 2.0 Core API (java.sql package) Scrollable ResultSets Streams JDBC 1.0 Specification Basic database connectivity JDBC 2.0 Standard Extension API (javax.sql package) DataSource Connection pooling Distributed transactions Rowsets

  6. Loading the Driver Class.forName(driverClassName).newInstance(); Class.forName(“com.mysql.jdbc.Driver”).newInstance(); • dynamically load a java class at runtime • executes newInstance() to create an object of class Driver calling the default constructor for the class. • The constructor executes code to register the class with the DriverManager

  7. Connecting to the Database Connection DriverManager.getConnection(String url); DriverManager.getConnection( “jdbc:mysql://localhost/accounts?user=root&password=cis384“);

  8. URL URL: <protocol>:<subprotocol>:<subname> jdbc mysql //localhost/accounts <subname>: //<host>[:<port>][/<databaseName>] //localhost/accounts //192.156.44.3/prod //db.mycompany.com/prod //db.mycompany.com:4544/prod when not specified, connector/J will default to port 3306.

  9. DriverManager -getConnection() method

  10. getConnection() – Example Properties info = new Properties(); info.setProperty(“user”, “username”); info setProperty(“password”, “pwd”); Connection con = DriverManager.getConnection(url, prop); OR String username=“username”; String password=“password”; Connection con = DriverManager.getConnection(url, username, password);

  11. Queries – Statement Object • used to send a SQL statement to the database • executes the SQL statement • returns back the results of the SQL statement

  12. createStatement()

  13. executeQuery() • no assumption is made on the validity of the query • if the SQL execute successfully it returns a ResultSet object containing rows from the database • if the SQL fails it will raise a SQLException

  14. Executing a Statement - Example ResultSet rs = stmt.executeStatement(“select name from pets”); ResultSet: Initial cursor position next() next()

  15. ResultSet Object • A table of data representing a database result set • maintains a cursor pointing to its current row of data • Initially the cursor is positioned before the first row • The next() method moves the cursor to the next row • next() returns false when there are no more rows in the ResultSet object • A default ResultSet object is not updatable and has a cursor that moves forward only

  16. Moving Through the ResultSet -Example while (rs.next()) { System.out.println(rs.getString((1))); } Fluffy Claws Buffy Fang Chirpy Whistler Slim Puffball

  17. Basic Getter Methods • int getInt(int columnIndex) • int getInt(String columnName) • String getString(int columnIndex) • String getString(String columnName) • Date getDate(int columnIndex) • Date getDate(String columnName)

  18. Handling Errors • Connector/J Driver throws a SQLException • errors connecting with the database • errors executing SQL statements • To know more about a single Exception use the SQLException methods • getMessage() • getSQLState() • getErrorCode()

  19. executeUpdate() method Returns either the row count for INSERT, UPDATE or DELETE statements, or 0 for SQL statements that return nothing

  20. Inserting a Row - Example Statement stmt = connection.createStatement(); int i= stmt.executeUpdate(“INSERT INTO pet VALUES(12, ’minou’, ’Gwen’, ’cat’)”);

  21. Updating a Row - Example Statement stmt = connection.createStatement(); int i= stmt.executeUpdate(“UPDATE pet SET owner=‘Lucy’ where owner= ‘Gwen’ ”);

  22. Deleting a Row - Example Statement stmt = connection.createStatement(); int i= stmt.executeUpdate(“DELETE FROM pet WHERE owner= ‘Gwen’ ”);

  23. Prepared Statements - SQL • ability to set up a statement once, and then execute it many times with different parameters. • replace building ad hoc query strings, and do so in a more efficient manner. • First implemented in the C API • Available in Connector/J server-side starting from version 3.1

  24. How databases execute queries • parse the query • invoke the optimizer to determine best query execution plan • caches the plan – query is the key to fetch plan from cache

  25. Prepared Statement - Example PREPARE sel_stmt FROM “SELECT name FROM pet WHERE id=?”; SET @pet_id=1; EXECUTE sel_stmt USING @pet_id

  26. JDBC – Dynamic Query Example Statement stmt = con.createStatement(); for int(i=1; i<=10; i++){ String stmtString = “select name from pet where id = “ +I; ResultSet rs = stmt.executeQuery(stmtString); while (rs.next()){ System.out.println(rs.getString(1)); } rs.close() } • statement is parsed by the database each time • new query plan is created for each select statement and cached (entire stmt being the key)

  27. JDBC – PreparedStatement PreparedStatement ps = con.prepareStatement( “select name from pet where id =?“ ); for int(i=1; i<=10; i++){ ps.setInt(1, i); -- variable binding ResultSet rs = ps.executeQuery(); while (rs.next()){ System.out.println(rs.getString(1)); } rs.close(); } • ? is called placeholder • query is parsed only once and only 1 execution plan is created and caches for it • executed many times after binding variables • MUCH MORE EFFICIENT!

  28. Placeholders- Setter methods

  29. Disconnecting from the database • close a connection to the database to release resources • Make sure you first close all component that use that connection • Close components in the reverse order you opened them. rs.close() stmt.close() conn.close()

More Related