Programming Tutorials

A simple JDBC application sample code

By: Ramlak in JDBC Tutorials on 2007-04-04  

The basic process for a single data retrieval operation using JDBC would be as follows.

  • a JDBC driver would be loaded;
  • a database Connection object would be created from using the DriverManager (using the database driver loaded in the first step);
  • a Statement object would be created using the Connection object;
  • a SQL Select statement would be executed using the Statement object, and a ResultSet would be returned;
  • the ResultSet would be used to step through (or iterate through) the rows returned and examine the data.

The following JDBC code sample demonstrates this sequence of calls.

JDBCSample.java

 import java.sql.*;

public class JDBCSample {
    public static void main(String args[]) {
        String connectionURL = "jdbc:postgresql://localhost:5432/movies;user=java;password=samples";
        // Change the connection string according to your db, ip, username and
        // password
        Connection con;
        try {
            // Load the Driver class.
            Class.forName("org.postgresql.Driver");
            // If you are using any other database then load the
            // right driver here.
            // Create the connection using the static getConnection
            // method
            con = DriverManager.getConnection(connectionURL);
            // Create a Statement class to execute the SQL statement
            Statement stmt = con.createStatement();
            // Execute the SQL statement and get the results in a
            // Resultset
            ResultSet rs = stmt.executeQuery("select moviename, releasedate from movies");
            // Iterate through the ResultSet, displaying two values
            // for each row using the getString method
            while (rs.next())
                System.out.println("Name=" + rs.getString("moviename") + " Date= " +
                        rs.getString("releasedate"));
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // Close the connection
            con.close();
        }
    }
}





Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in JDBC )

Latest Articles (in JDBC)