100 likes | 278 Views
JDBC Part I. Java. JDBC?. Java Database Connectivity JDBC is an API for the Java programming language that defines how a client may access a database It provides methods for querying and updating data in a database JDBC is oriented towards relational databases. Java Database Drivers.
E N D
JDBC Part I Java
JDBC? • Java Database Connectivity • JDBC is an API for the Java programming language that defines how a client may access a database • It provides methods for querying and updating data in a database • JDBC is oriented towards relational databases
Java Database Drivers • In order to work with relational tables, the program must establish a communication link to the relational database that contains these tables • A database driver provides this link • We are going to use the JDBC Thin Driver
Connecting to a Database First line: import java.sql.*; // in Main method try { Connection conn = DriverManager.getConnection( "jdbc:oracle:thin:@classdb.jccc.edu:1521/cs260", “username", “xxxx"); System.out.println(“connected!”); …. } catch(Exception e) { e.printStackTrace(); } • Open Eclipse and follow along…. • Need to include ojdbc6.zip in Java build path
Using JDBC • Remember in SQL, our select statements returned a result table (aka result set) • We will use the same approach within our Java program • We will create and execute SQL • We will capture the results of the SQL execution within a result set (i.e. an object)
Creating a Result Set Statement statement = conn.createStatement ( ); ResultSet rs = statement.executeQuery ( “Select course_no From student.course” ); Look at this statement, what does it do? Look at this statement, what does it do?
How to move a cursor through a Result Set What is a cursor? while ( rs.next ( ) ) { // code that processes each record of the result set } How does this while loop work?
How to return data from a Result Set Using column names: while ( rs.next ( ) ) { int courseNo = rs.getInt(“Course_No”); System.out.println(“CNo: “ + courseNo); } Explain the above code Using column indexes: while ( rs.next ( ) ) { int courseNo = rs.getInt(1); System.out.println(“CNo: “ + courseNo); } Explain the above code Pick one approach and implement it within your program. Try it.
Practice • Implement both column index and column name code. Run it. What happened and why? • Using either column index or column name, display the number of records you processed • Display the course number and description
For April 21st • Continue with JDBC • Quiz • Project #14 due