We now have an overview of JDBC. The rest of this chapter will concentrate on writing abstractions that sit above JDBC, making database accesses feel more natural. Before we do this, let's summarize what we have seen so far.
We have used three JDBC classes:
Connection
class represents a connection to a specific SQL database. Instantiate a connection as follows:import java.sql._ Class.forName("com.mysql.jdbc.Driver")val connection = DriverManager.getConnection( "jdbc:mysql://127.0.0.1:3306/test", "root", // username when connecting "" // password )
Our main use of Connection
instances has been to generate PreparedStatement
objects:
connection.prepareStatement("SELECT * FROM physicists")
PreparedStatement
instance represents a SQL statement about to be sent to the database. It also represents the template for a SQL statement with placeholders for values yet to be filled in. The class exposes the following methods:
|
This sends the statement to the database. Use this for SQL statements that modify the database and do not return any data, such as |
|
This sends the statement to the database. Use this for SQL statements that return data (predominantly, the |
|
The |
|
Fill in the placeholder values in the One common use case for these is in a batch update or insert: we might have a Scala list of objects that we want to insert into the database. We fill in the placeholders for each object in the list using the |
|
This sets a particular item in the statement to |
ResultSet
instance represents a set of rows returned by a SELECT
or SHOW
statement. ResultSet
exposes methods to access fields in the current row:
|
These methods get the value of the |
|
These methods get the value of a specific field, which is indexed by the column name. |
|
This returns whether the last column read was |
The ResultSet
instance exposes the .next
method to move to the next row; .next
returns true
until the ResultSet
has advanced to just beyond the last row.