Saturday, 9 February 2013

Start Using JDBC

What is JDBC?

JDBC stands for Java Database Connectivity, is a set of Java API for accessing the relational databases from Java program. The Java API enables the programmers to execute the SQL statements against the JDBC complaint database.

JDBC allows the programmers to quickly develop small Java applications that interact with the databases. 

To develop an application programmer has to:

  1. Develop the code to connect to the database 
  2. Write the code to execute the query. 

Once the query is successfully executed and result is retrieved from the database, programmer can read the data programmatically from the result set object. 

How dose it Work ?
you will find the steps below sorted in steps :

  1. Load the Driver class.
  2. Create the connection using the static getConnection method
  3. Create a Statement class to execute the SQL statement
  4. Execute the SQL statement and get the results in a Resultset
  5. Iterate through the ResultSet, 

Code Example:

  1. // Change the connection string according to your db, ip, username and password
  2. String connectionURL = "jdbc:postgresql://localhost:5432/movies;user=java;password=samples";

  3. try {
  4.  
  5.     // 1_ Load the Driver class.
  6.     Class.forName("org.postgresql.Driver");
  7.     // If you are using any other database then load the right driver here.
  8.  
  9.     // 2_ Create the connection using the static getConnection method
  10.     Connection con = DriverManager.getConnection (connectionURL);
  11.  
  12.     //3_ Create a Statement class to execute the SQL statement
  13.     Statement stmt = con.createStatement();
  14.  
  15.     //4_ Execute the SQL statement and get the results in a Resultset
  16.     ResultSet rs = stmd.executeQuery("select * from table ");
  17.  
  18.     // 5 _Iterate through the ResultSet, displaying two values
  19.     // for each row using the getString method
  20.  
  21.     while (rs.next())
  22.         System.out.println("Name= " + rs.getString("moviename") + " Date= " + rs.getString("releasedate");
  23. }
  24. catch (SQLException e) {
  25.     e.printStackTrace();
  26. }
  27. catch (Exception e) {
  28.     e.printStackTrace();
  29. }
  30. finally {
  31.     // Close the connection
  32.     con.close();
  33. }

No comments:

Post a Comment