Java JDBC driver connection string syntax and examples

JDBC is an API standard that allows Java code to access underlying database with an uniform interface. Various database vendors will provide their own implementation to let Java user to access them. If you ever used Log4j, you get the idea. Theoretically if you use JDBC to access database, you can replace your database system without change your Java code. So JDBC is an abstraction of how to interact with RDBMS.

Some databases provides independent JDBC driver like MySQL and Oracle. Small and lightweight database like H2 ship the driver along with the database itself.

With JDBC driver you can connect to almost any database with the same API, the only thing you need is a connection string. The connection string consists of three parts: the jdbc, the database vendor name and a url in which you can speicify the user name, password or database name. Each database has its own syntax to specify the third part, the url. They are general resemblance with minor differences.

But there are so many database products you may need to use in your application, you may forget the syntax. Here is a list of JDBC driver connection string examples for major databases.

MySQL

The MySQL connection string just like the Web page URL you can see in your browser address bar, the protocol is jdbc:mysql, the Web page has the http protocol, the rest are the same.

 
jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&user=root&password=*****
 

The test is database name you want to connect to, the rest is pairs of key value configurations like encoding, user name and password. To see the full list MySQL connection options.

H2 database

H2 database supports multiple connection modes and settings. It can be embedded or in memory or used as rapid prototyping and testing. There are more ways to specify the connection url for different purpose

Embedded local connection

 
jdbc:h2:~/test
 

You are specifying a file as your database on local file system, the '~' means the user home. Without it means store the file in current working directory

Use a memory database

 
jdbc:h2:mem
 

Configurations are separated by ;

 
jdbc:h2:~/test;DB_CLOSE_DELAY=-1
 

See the manual http://www.h2database.com/h2.pdf for more details.

PostgreSQL

PostgreSQL and MySQL are similar with each other.

 
jdbc:postgresql://localhost/test
jdbc:postgresql://localhost/test?user=fred&password=secret&ssl=true
 

SqlServer

Similar to H2 database

 
jdbc:sqlserver://localhost;user=MyUserName;password=*****