Basic JDBC Celsina Bignoli [email protected]. What is JDBC Industry standard for database-...

29
Basic JDBC Celsina Bignoli [email protected]

Transcript of Basic JDBC Celsina Bignoli [email protected]. What is JDBC Industry standard for database-...

Basic JDBC

Celsina [email protected]

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

SybaseDB

JavaApplication

DriverManager

Sybase Driver MySQL Driver Oracle Driver

MySQLDB

Oracle DB

JDBC Drivers

• Vendor-specific implementation of the JDBC interfaces

• Transparent to the database application developers

JDBC specifications

JDBC 2.0 Core API(java.sql package)

Scrollable ResultSetsStreams

JDBC 2.0 Standard Extension API(javax.sql package) DataSource Connection pooling Distributed transactions Rowsets

JDBC 2.0 Specification

JDBC 1.0 SpecificationBasic database connectivity

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

Connecting to the DatabaseConnection DriverManager.getConnection(String url);

DriverManager.getConnection(

“jdbc:mysql://localhost/accounts?user=root&password=cis384“);

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.

DriverManager -getConnection() method

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 using the specified properties.

static Connection getConnection(String url,

String user,

String password)

Attempts to establish a connection to the given database URL as used identified by password.

getConnection() – Example

Properties info = new Properties();

info.setProperty(“user”, “username”);

info setProperty(“password”, “pwd”);

Connection con = DriverManager.getConnection(url, prop);

ORString username=“username”;

String password=“password”;

Connection con = DriverManager.getConnection(url, username, password);

Queries – Statement Object

• used to send a SQL statement to the database

• executes the SQL statement

• returns back the results of the SQL statement

createStatement()Statement createStatement ()

Creates a Statement object for sending SQL statements to the database.

executeQuery()

ResultSet executeQuery(String sql)

Executes the given SQL statement, which returns a single ResultSet object

•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

Executing a Statement - Example

ResultSet rs =

stmt.executeStatement(“select name from pets”);

ResultSet:

Fluffy

Claws

Buffy

Fang

Chirpy

Whistler

Slim

Puffball

Initial cursor position

next()

next()

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

Moving Through the ResultSet -Example

while (rs.next()) { System.out.println(rs.getString((1))); }

FluffyClawsBuffyFangChirpyWhistlerSlimPuffball

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)

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()

executeUpdate() method

int executeUpdate (String sql)

Creates a Statement object for sending SQL statements to the database.

Returns either the row count for INSERT, UPDATE or DELETE statements, or 0 for SQL statements that return nothing

Inserting a Row - Example

Statement stmt = connection.createStatement();

int i= stmt.executeUpdate(“INSERT INTO pet VALUES(12, ’minou’, ’Gwen’, ’cat’)”);

Updating a Row - Example

Statement stmt = connection.createStatement();

int i= stmt.executeUpdate(“UPDATE pet SET owner=‘Lucy’ where owner= ‘Gwen’ ”);

Deleting a Row - Example

Statement stmt = connection.createStatement();

int i= stmt.executeUpdate(“DELETE FROM pet WHERE owner= ‘Gwen’ ”);

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

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

Prepared Statement - Example

PREPARE sel_stmt FROM “SELECT name FROM pet WHERE id=?”;

SET @pet_id=1;

EXECUTE sel_stmt USING @pet_id

name

Fluffy

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)

JDBC – PreparedStatementPreparedStatement 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!

Placeholders- Setter methods

void setInt(int parameterIndex, int value)

void setString(int parameterIndex, String value)

void setDate(int parameterIndex, java.sql.Date value)

void setTimestamp(int parameterIndex, java.sql.Timestamp value)

void setLong(int parameterIndex, long value)

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()