Monday 19 September 2011

A simple JDBC application sample code

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
  1. import java.sql.*
  2.  
  3. public class JDBCSample {
  4.  
  5. public static void main( String args[]) {
  6.  
  7. String connectionURL = "jdbc:postgresql://localhost:5432/movies;user=java;password=samples";
  8. // Change the connection string according to your db, ip, username and password
  9.  
  10. try {
  11.  
  12.     // Load the Driver class.
  13.     Class.forName("org.postgresql.Driver");
  14.     // If you are using any other database then load the right driver here.
  15.  
  16.     //Create the connection using the static getConnection method
  17.     Connection con = DriverManager.getConnection (connectionURL);
  18.  
  19.     //Create a Statement class to execute the SQL statement
  20.     Statement stmt = con.createStatement();
  21.  
  22.     //Execute the SQL statement and get the results in a Resultset
  23.     ResultSet rs = stmd.executeQuery("select moviename, releasedate from movies");
  24.  
  25.     // Iterate through the ResultSet, displaying two values
  26.     // for each row using the getString method
  27.  
  28.     while (rs.next())
  29.         System.out.println("Name= " + rs.getString("moviename") + " Date= " + rs.getString("releasedate");
  30. }
  31. catch (SQLException e) {
  32.     e.printStackTrace();
  33. }
  34. catch (Exception e) {
  35.     e.printStackTrace();
  36. }
  37. finally {
  38.     // Close the connection
  39.     con.close();
  40. }
  41. }
  42. }

No comments:

Post a Comment

Complete Details about eLitmus pH Test at Rs:699/- Share your java material and fresher interview Information for us to Help Others... mail to : vhkrishnan.v@gmail.com