To connect using java.sql.DriverManager
you need a JDBC url to connect to your database. JDBC urls are database specific, but they are all of the form
jdbc:<subprotocol>:<subname>
Where <subprotocol>
identifies the driver or database (for example postgresql
, mysql
, firebirdsql
, etc), and <subname>
is subprotocol-specific.
You need to check the documentation of your database and JDBC driver for the specific url subprotocol and format for your driver.
A simple example to create a connection to a database with the url jdbc:somedb://localhost/foobar
:
try (Connection connection = DriverManager.getConnection(
"jdbc:somedb://localhost/foobar", "anna", "supersecretpassword")) {
// do something with connection
}
We use a try-with-resources here so the connection is automatically closed when we are done with it, even if exceptions occur.
On Java 6 (JDBC 4.0) and earlier, try-with-resources is not available. In those versions you need to use a finally
-block to explicitly close a connection:
Connection connection = DriverManager.getConnection(
"jdbc:somedb://localhost/foobar", "anna", "supersecretpassword");
try {
// do something with connection
} finally {
// explicitly close connection
connection.close();
}
JDBC 4.0 (Java 6) introduced the concept of automatic driver loading. If you use Java 5 or earlier, or an older JDBC driver that does not implement JDBC 4 support, you will need to explicitly load the driver(s):
Class.forName("org.example.somedb.jdbc.Driver");
This line needs to occur (at least) once in your program, before any connection is made.
Even in Java 6 and higher with a JDBC 4.0 it may be necessary to explicitly load a driver: for example in web applications when the driver is not loaded in the container, but as part of the web application.
Alternatively you can also provide a Properties
object to connect:
Properties props = new Properties();
props.setProperty("user", "anna");
props.setProperty("password", "supersecretpassword");
// other, database specific, properties
try (Connection connection = DriverManager.getConnection(
"jdbc:somedb://localhost/foobar", props)) {
// do something with connection
}
Or even without properties, for example if the database doesn't need username and password:
try (Connection connection = DriverManager.getConnection(
"jdbc:somedb://localhost/foobar")) {
// do something with connection
}