Database url contains 3 parts -- protocol name : vendor name : database specific connection details.
JDBC URL |
For example, the followings are valid jdbc urls:
- jdbc:mysql://localhost/Contact
- jdbc:derby:Client
- jdbc:oracle:thin:@126.133.143.1:Role
- jdbc:mysql://localhost:3306/Ticket?useUnicode=true&characterEncoding=utf8
With a jdbc url, we can call factory method DriverManager.getConnection(url) to get an connection. Optionally, username and password can be supplied as parameters of getConnection.
Drivermanager looks through the class path for JARs that contain a Driver. If not find any Driver that can handle the JDBC URL, it throws a SQLException. So make sure the driver jar is in your class path when invoking the java program.
OCPJP>cat JDBCUrlTest.java
import java.sql.*;
public class JDBCUrlTest {
public static void main(String... args) throws SQLException {
Connection connection = DriverManager.getConnection("jdbc:derby:social;create=true");
System.out.println(connection);
}
}
OCPJP>
OCPJP>javac JDBCUrlTest.java
OCPJP>java JDBCUrlTest
Exception in thread "main" java.sql.SQLException: No suitable driver found for jdbc:derby:social;create=true
at java.sql.DriverManager.getConnection(DriverManager.java:689)
at java.sql.DriverManager.getConnection(DriverManager.java:270)
at JDBCUrlTest.main(JDBCUrlTest.java:4)
OCPJP>java -cp "${JAVA_HOME}/db/lib/derby.jar:." JDBCUrlTest
org.apache.derby.impl.jdbc.EmbedConnection40@1331923253 (XID = 166), (SESSIONID = 1), (DATABASE = social), (DRDAID = null)
OCPJP>
for a more complexed example, check out this lab.