Slide navigation: Forward with space bar, → arrow key, or PgDn. Backwards with ← or PgUp.
Copyright © Cay S. Horstmann 2016
java -jar derby/lib/derbyrun.jar server start
derbyclient.jar
for Derby.jdbc:derby://localhost:1527/databaseName;create=true
String url = "jdbc:derby://localhost:1527/COREJAVA;create=true"; String username = "app"; String password = "secret"; Connection conn = DriverManager.getConnection(url, username, password);
Connection
object to create SQL statements.@Resource(name="jdbc/corejava") private DataSource source; ... Connection conn = source.getConnection();
java -jar /opt/jdk1.8.0/db/lib/derbyrun.jar server start & java -classpath /opt/jdk1.8.0/db/lib/derbyrun.jar:. test.TestDB java -jar /opt/jdk1.8.0/db/lib/derbyrun.jar server shutdown
Statement
object:
Statement stat = conn.createStatement();
INSERT
, UPDATE
, DELETE
), call the executeUpdate
method:
String command = "UPDATE Books" + " SET Price = Price - 5.00" + " WHERE Title NOT LIKE '%Introduction%'"; int rows = stat.executeUpdate(command);
executeQuery
to issue a SELECT
query:
ResultSet result = stat.executeQuery("SELECT * FROM Books");
execute
to issue arbitrary SQL commands.Connection
object can produce one or more Statement
objects.
Statement
at a time.DatabaseMetaData.getMaxStatements
to find out.Statement
object for multiple queries.Statement
can have at most one open ResultSet
.
Statement
, an open result set is closed.
Statement.closeOnCompletion
method closes the statement as soon as an open result set is closed.Connection
, all statements are closed.SQLException
has a chain of SQLException
objects.SQLException
class extends the Iterable<Throwable>
interface.for (Throwable t : sqlException) { do something with t }
SQLException.getSQLState
method yields a string that is standardized by either X/Open or SQL:2003.
DatabaseMetaData.getSQLStateType
to find out which standard is used by your driver.SQLWarning w = stat.getWarning(); while (w != null) { do something with w w = w.nextWarning(); }
java -jar /opt/jdk1.8.0/db/lib/derbyrun.jar server start & java -classpath /opt/jdk1.8.0/db/lib/derbyrun.jar:. exec.ExecSQL Authors.sql java -classpath /opt/jdk1.8.0/db/lib/derbyrun.jar:. exec.ExecSQL Publishers.sql java -classpath /opt/jdk1.8.0/db/lib/derbyrun.jar:. exec.ExecSQL Books.sql java -classpath /opt/jdk1.8.0/db/lib/derbyrun.jar:. exec.ExecSQL BooksAuthors.sql java -classpath /opt/jdk1.8.0/db/lib/derbyrun.jar:. query.QueryTest java -jar /opt/jdk1.8.0/db/lib/derbyrun.jar server shutdown
ResultSet
:
ResultSet rs = stat.executeQuery("SELECT * FROM Books")
while (rs.next()) { look at a row of the result set }
get
methods:
String isbn = rs.getString(1); // The first (!) column double price = rs.getDouble("Price");
String query = "SELECT * FROM Books WHERE Books.Title = " + title; // Don't—or you may become the victim of SQL injection
String query = "SELECT * FROM Books WHERE Books.Title = ?"; PreparedStatement stat = conn.prepareStatement(query); stat.setString(1, title); ResultSet rs = stat.executeQuery();
PreparedStatement
becomes invalid after closing the Connection
that created it.
{d '2008-01-24'} {t '23:59:59'} {ts '2008-01-24 23:59:59.999'}
{fn left(?, 20)} {fn user()}
{call PROC1(?, ?)} {call PROC2} {? = call PROC3(?)}
{oj ...}
escape lets you formulate outer joins in a database-independent way.%
:
... WHERE Books.title LIKE %!%% {escape '!'}
Id INTEGER AUTO_INCREMENT
Id INTEGER GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1)
INSERT
statement:
stat.executeUpdate(insertStatement, Statement.RETURN_GENERATED_KEYS); ResultSet rs = stat.getGeneratedKeys(); if (rs.next()) { int key = rs.getInt(1); Do something with key }
SELECT
statements together.boolean isResult = stat.execute(command); boolean done = false; while (!done) { if (isResult) { ResultSet result = stat.getResultSet(); do something with result } else { int updateCount = stat.getUpdateCount(); if (updateCount >= 0) do something with updateCount else done = true; } if (!done) isResult = stat.getMoreResults(); }
ResultSet.next
method iterates over the rows of a result set.Statement stat = conn.createStatement(type, concurrency); PreparedStatement stat = conn.prepareStatement(command, type, concurrency);
Value |
Explanation |
---|---|
|
The result set is not scrollable (default). |
|
The result set is scrollable but not sensitive to database changes. |
|
The result set is scrollable and sensitive to database changes. |
|
The result set cannot be used to update the database (default). |
|
The result set can be used to update the database. |
rs.previous() rs.relative(n) rs.absolute(n)
getCurrentRow
method yields the current row number (starting at 1) or 0 if the cursor is before the first or after the last row.update
methods to change a column value:
double price = rs.getDouble("Price");
rs.updateDouble("Price", price + increase);
rs.updateRow(); // Call updateRow
to store the changes
rs.moveToInsertRow(); call rs.updateXxx(...) rs.insertRow(); rs.moveToCurrentRow();
ResultSet.deleteRow
method removes the row from both the result set and the database.RowSetFactory factory = RowSetProvider.newFactory(); CachedRowSet crs = factory.createCachedRowSet();
ResultSet result = . . .; crs.populate(result); conn.close(); // now OK to close the database connection
crs.acceptChanges(conn)
, passing a new Connection
object.crs.setURL("jdbc:derby://localhost:1527/COREJAVA"); crs.setUsername("app"); crs.setPassword("secret");
crs.setCommand("SELECT * FROM Books WHERE Title = ?"); crs.setString(1, title); crs.execute();
crs.acceptChanges()
without a Connection
parameter.conn.setAutoCommit(false); Statement stat = conn.createStatement(); stat.executeUpdate(command1); stat.executeUpdate(command2); ... conn.commit();
conn.rollback();
INSERT
statements.executeUpdate
, call the addBatch
method:
String command = "CREATE TABLE . . ." stat.addBatch(command); while (...) { command = "INSERT INTO . . . VALUES (" + . . . + ")"; stat.addBatch(command); }
int[] counts = stat.executeBatch(); // Yields row counts for all submitted statements
DatabaseMetaData
object from a connection:
DatabaseMetaData meta = conn.getMetaData();
ResultSet mrs = meta.getTables(null, null, null, new String[] { "TABLE" });
while (mrs.next()) System.out.println(mrs.getString(3));
meta.supportsCatalogsInPrivilegeDefinitions() meta.nullPlusNonNullIsNull()
ResultSetMetaData
interface has methods to describe a result set.ResultSet rs = stat.executeQuery("SELECT * FROM " + tableName); ResultSetMetaData meta = rs.getMetaData(); for (int i = 1; i <= meta.getColumnCount(); i++) { String columnName = meta.getColumnLabel(i); int columnWidth = meta.getColumnDisplaySize(i); ... }
java -jar /opt/jdk1.8.0/db/lib/derbyrun.jar server start & java -classpath /opt/jdk1.8.0/db/lib/derbyrun.jar:. view.ViewDB java -jar /opt/jdk1.8.0/db/lib/derbyrun.jar server shutdown