JDBC connection example: How do I connect to a SQL database?

Java/JDBC connection FAQ: How do I connect to a database using Java and JDBC?

Let's take a look at a JDBC database connection example. In this example I'll connect to a Postgresql database, but as you'll see from the code and other examples on this web site, the steps are always very similar.

A Java/JDBC Postgresql database connection example

To get a JDBC connection to a PostgreSQL database do this:

  Class.forName("org.postgresql.Driver");
  String url = "jdbc:postgresql://host/database";
  Connection conn = DriverManager.getConnection(url,"username", "password");

Of course you must specify your own values for the host, database, username, and password.

Note that the PostgreSQL URL can be of these forms:

  jdbc:postgresql:database
  jdbc:postgresql://host/database
  jdbc:postgresql://host:port/database

The phrase host refers to the computer you are trying to connect to, i.e., the computer that has PostgreSQL installed. It can be localhost for your computer, or a valid name or TCP/IP address for a remote computer system.

A Java MySQL database connection example

Cool. How do I connect to a MySQL database?

As mentioned above, the Java/JDBC code you use to connect to databases is always very similar. In fact, to connect to a MySQL database all you have to do is change the database Driver and URL strings. The code below shows the name of the Driver and the format of the URL to connect to a MySQL database.

  String driver = "org.gjt.mm.mysql.Driver";
  String url = "jdbc:mysql://host/database";

Java JDBC database connection examples - Summary

I hope these Java database connection examples using Postgresql and MySQL have been helpful.

Comments