JDBC – Java Database Connectivity @ 1

JDBC is an API for Java and it defines how your Java application make connection to the database in order to query or update the data.

In the following example, it shows you how to get a value from the database using the JDBC API. To make use of the API, you have to download the JDBC driver of your database. Postgresql Database is used in this example. so the postgresql-8.4-701.jdbc3.jar is added to the eclipse project.

Selector.java

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Selector {
	public static void main(String[] args) {
		System.out.println("*** Start ***");
		
		// Set the JDBC driver and database driver path
		String driver = "org.postgresql.Driver";
		String url = "jdbc:postgresql://localhost:5432/spain";
		
		// Set the database username and password
		String user = "<username>";
		String password = "<password>";
		
		// Create the SQL statement
		StringBuilder sb = new StringBuilder("");
		sb.append("SELECT city_name ");
		sb.append("  FROM cities ");
		sb.append(" WHERE city_id  = 100;");
		
		// Load the JDBC driver
		try	{
			Class.forName(driver);
		} catch(Exception E) {
			System.out.println("Unable to load JDBC driver: " + driver);
		}
		
		// Execute the SQL statement
		try {
			Connection con = DriverManager.getConnection(url,user,password);
			Statement smt = con.createStatement();
			ResultSet rst = smt.executeQuery(sb.toString());
			while (rst.next()) {
				System.out.println("I will go to " + rst.getString(1) + " on August!");
			}
			rst.close();
			smt.close();
			con.close();
		} catch(SQLException SE) {
			System.out.println("Fail to execute the SQL statement");
		}
		
		System.out.println("***  End  ***");
	}
}



Expected output

*** Start ***
I will go to Barcelona on August!
*** End ***

You can find more details about the JDBC API at JDBC Tutorial at Sun.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.