Lecture 6 - JDBC Flashcards
What is JDBC and what is it for?
Gives a standard API for databases (for programming access)
What does java.sql.DriverManager do?
loads JDBC drivers and creates Connection objects
What does DriverManager.getConnection(String url) do?
And what is the format of the URL?
Looks for the driver to handle the URL connection.
jdbc:subprotocol:datasourcename
NOTE: username + password can be given in the URL.
What is jdbc.drivers?
A system property that drivers are loaded into.
What exception do JDBC methods usually throw?
SQLException
What is a statement object?
Create SQL Statement from the connection
to return Statement object
Used to query
How do we connect with properties to avoid hard-coding?
Create new java.util.Properties object (e.g.
options)
Use options.load(new FileInputStream(..))
OR
Query a property with options.getProperty
How do we query a database?
- create a statement using connection.createStatement();
OR prepareStatement with SQL_command template that can be filled with values (useful for user input)
- statement.executeQuery(some_SQL_code)
- a result set is returned
How do we create and fill placeholder values for prepareStatement()?
?
setType(position, value)
– E.g. setInt, setString, setDate, …
How do we work with ResultSet object?
Data is organized into columns and rows
call next() to get first row
returns false if no next row
column data obtained with getType()
(Ex: getInt, getString, getDate)
What is the issue with JDBC and why would be have to learn Jakarta Persistence?
Major issue is connections are expensive.
This is solved by creating a connection pool using javax.sql.DataSource.
ResultSet can return object that contains
information about the returned results (T or F)
True
ResultSetMetaData
Why do we NOT make a SQL query by concatenating user input?
Use prepared statements instead, will prevent attacks and SQL exceptions.
How can we access SQL warnings?
Less severe errors are not thrown, but generate
SQLWarning or DataTruncation warnings
getWarnings() method of any Connection,
Statement, ResultSet object