Presentation is loading. Please wait.

Presentation is loading. Please wait.

Accessing Database using JDBC. JDBC Objectives Gain basic knowledge of Java JDBC Become familiar with the basics of interacting with a database using.

Similar presentations


Presentation on theme: "Accessing Database using JDBC. JDBC Objectives Gain basic knowledge of Java JDBC Become familiar with the basics of interacting with a database using."— Presentation transcript:

1 Accessing Database using JDBC

2 JDBC Objectives Gain basic knowledge of Java JDBC Become familiar with the basics of interacting with a database using SQL constructs Contents What is a Relational Database? What is JDBC? JDBC Drivers Connecting to the Database Executing Common SQL Commands Closing the Database Connection Meta Data

3 What is a Relational Database? A relational database is a powerful data storage and retrieval system Databases can be described as a collection of tables Tables are made up of rows and columns Structured Query Language (SQL) allows users to manipulate data in relational databases

4 SQL Fundamentals SQL (Structured Query Language) is a powerful set-oriented language that can interact with any relational database for the manipulation, definition and control of data. All the major database vendors support SQL Example SQL queries: SELECT * FROM BooksTable SELECT Title, [Author Name], Description FROM BooksTable WHERE Title='Look for me‘ INSERT INTO BooksTable VALUES ('Book Name', 'P.G. Author', 'Brief Description')

5 What is JDBC? Provides universal access to many relational databases An interface which allows Java code to execute SQL statements inside relational databases Sybase Oracle DB2 JDBC Code JAVA Application

6 What is JDBC? (cont.) The JDBC API provides applications with a universal database language With the JDBC API, programmers can construct SQL statements and embed them inside Java code The query results are stored in Java variables and errors are stored in Java exceptions The JDBC API is in the java.sql package

7 ODBC Open Database Connectivity is an application programming interface (API) for database access ODBC is not a platform independent API The main proponent and supplier of ODBC programming support is Microsoft By using ODBC statements in a program, you can access data in a number of different databases including Access, dBase, Excel, and Text In addition to the ODBC software, a separate driver is needed for each database to be accessed

8 The JDBC-ODBC Bridge Allows Java code to use the C/C++ interface of ODBC it means that JDBC can access many different database products JDBC Data processing utilities Java Code jdbc-odbc bridge odbc driver

9 The JDBC-ODBC Bridge The JDBC-ODBC bridge comes free with the JDK: called sun.jdbc.odbc.JdbcOdbcDriver The ODBC driver for Microsoft Access comes with MS Office so it is easy to connect Java and Access

10 JDBC Drivers The JDBC driver essentially hides the vendor specific code from the application developer The JDBC driver is the mediator between the Java application and the database

11 Types of JDBC Drivers There are 4 types of JDBC drivers each using different protocols to access the database 1.JDBC-ODBC Bridge Provides a gateway to the ODBC API. ODBC actually accesses the database This driver generally requires software to be installed on the client systems 2.Native API translate Java to the database’s own API

12 Types of JDBC Drivers 3. Net Protocol All-Java Translates JDBC calls into a database- independent network protocol which is then translated to a database protocol by a server. An extremely flexible 100% Pure Java driver. It does not require code to be installed on the client and will provide access to multiple databases 4.Native Protocol All-Java Translates JDBC calls into a database dependent network protocol used by databases directly Talks directly to the database using Java sockets This is a 100% Pure Java solution that generally comes from the database vendor

13 JDBC Drivers A searchable list of drivers (freeware, shareware, and commercial) can be found at: http://www.javasoft.com/products/jdbc/drivers

14 JDBC Pseudo Code 1.load the JDBC driver 2.Specify the name and location of the database being used 3.Connect to the database with a Connection object 4.Execute a SQL query using a Statement object 5.Get the results in a ResultSet object 6.Finish by closing the ResultSet, Statement and Connection objects

15 Pseudocode as a Diagram DriveManagerConnectionStatementResultSet creates Driver SQL data make link to driver

16 Connecting to the Database Establishing a database connection Load the driver Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Open a database connection Connection conn = DriveManager.getConnection(url,”myLogin”, “myPasswd”); Connection Object Database opened, return the connection

17 Name the Database The name and location of the database is given as a URL the details of the URL vary depending on the type of database that is being used

18 JDBC Database URL jdbc:odbc: //host.domain.com: 2048 /data/file The protocolThe machine holding the database The port used for the connection The path to the database on the machine e.g. jdbc:odbc:Books

19 JDBC Statement Creating a JDBC connection Creating a JDBC statement A Statement object is used to send the SQL statement to the database The Statement object must be created by using the open Connection object Connection con = DriverManager.getConnection("jdbc:odbc:bookdb","",""); Connection con = DriverManager.getConnection("jdbc:odbc:bookdb","",""); Statement st = conn.createStatement(): ResultSet rs = st.executeQuery(“select * from Authors”); st.close();

20 JDBC Statements (cont.) There are 2 important Statement methods executeQuery(String SQLstatement) Executes a SQL SELECT statement. Returns a ResultSet object executeUpdate(String SQLstatement) Executes a SQL INSERT, UPDATE or DELETE statement Before reusing a Statement object, call the close() method

21 ResultSet Object The ResultSet object contains the rows retrieved from the database query To access each row use ResultSets’s next() method This method moves a database cursor sequentially through the rows retrieved from the query while(rs.next()) { name = rs.getString(“id"); age = rs.getInt(“name"); System.out.println(id + " " + name); } while(rs.next()) { name = rs.getString(“id"); age = rs.getInt(“name"); System.out.println(id + " " + name); }

22 ResultSet Object Cursor operations: first() last() next() previous(), etc. Typical code: while (rs.next()){ //process the row; } 23 5 17 98 John Mark Paul Peter cursor

23 SimpleJDBC.java // SimpleJDBC.java // Displays the firstnames and lastnames // of the Authors table in the Books db import java.sql.*; public class SimpleJDBC { public static void main(String[] args) { // The URL for the Books database. // ’Protected' by a login and password. String url = "jdbc:odbc:Books"; String username = "anonymous"; String password = "guest";

24 try { // load the JDBC-ODBC Bridge driver Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // connect to db using DriverManager Connection conn = DriverManager.getConnection(url, username, password); // Create a statement object Statement statement = conn.createStatement(); // Execute the SQL query ResultSet rs = statement.executeQuery( "SELECT lastName, firstName FROM Authors" );

25 //Print the result set while(rs.next()) { System.out.println(rs.getString("lastName") + ", " + rs.getString("firstName")); } // Close down statement.close(); conn.close(); } catch (ClassNotFoundException cnfex ) { System.err.println( "Failed to load JDBC/ODBC driver." ); cnfex.printStackTrace(); System.exit( 1 ); // terminate program } catch (SQLException sqlex ) { System.err.println( sqlex ); sqlex.printStackTrace(); } } // end of main() } // end of SimpleJDBC class

26 Books.mdb as an ODBC Data Source 1. Click on “32 bit ODBC” in the Control Panel. This displays the ODBC Data Sources Administrator

27 2. Press Add to add a data source and select Microsoft Access Driver (*.mdb). Press “Finish”.

28 3. Type in a source name, description, and press Select to browse to set the path to the Books.mdb file. Now click on Advanced

29 4. Type in a username and password (guest) Click Ok

30 Table in Books.mdb Publishers PublisherID PublisherName Titles ISBN Title EditionNumber YearPublished Description PublisherID AuthorISBN ISBN AuthorID Authors AuthorID FirstName LastName YearBorn 1 8 8 8 1 1


Download ppt "Accessing Database using JDBC. JDBC Objectives Gain basic knowledge of Java JDBC Become familiar with the basics of interacting with a database using."

Similar presentations


Ads by Google