What is JDBC?
Steps for building a simple JDBC application
A Simple Program to demonstrate the JDBC application working:
//STEP 1. Import packages
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.Date;
import java.sql.SQLException;
public class FirstQuery {
public static void main(String[] args) {
//Define Connection variable
Connection conn = null;
//Begin standard error handling
try{
//STEP 2: Register JDBC driver
String driver = “oracle.jdbc.driver.OracleDriver”; //for oracle database
Class.forName(driver);
//STEP 3: Open a connection
System.out.println(“Connecting to database…”);
String jdbcUrl = “jdbc:oracle:thin:@localhost:1521:XE”;
/* this url will be different for the different databases */
String user = “username”; // username and password for the database authentication
String password = “password”;
conn = DriverManager.getConnection(jdbcUrl,user,password);
//STEP 4: Execute a query
Statement stmt = conn.createStatement();
String sql;
sql = “SELECT SSN, Name, Salary, Hiredate FROM Employees”;
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
int ssn= rs.getInt(“ssn”);
String name = rs.getString(“name”);
//Retrieve by column index as an example
double salary = rs.getDouble(3);
Date date = rs.getDate(4);
//Display values
System.out.print(“SSN: ” + ssn);
System.out.print(“, Name: ” + name);
System.out.print(“, Salary: $” + salary);
System.out.println(“, HireDate: ” + date);
}
//STEP 6: Clean?up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
System.out.println(“Finished!”);
}//end main
}
The Expected Output after you have created the databse with some values of these columns:
This was just a simple demonstration program to just give some idea about the JDBC connectivity.
In the later posts, the more detailed and programs for entering the data in the databse, updating and creating the database using either Statement or preparedStatement objects.
| For additional affordable web design toronto specifics, look at intelligentwebsitetechnologies.com. |
| For a good Attracta SEO review, consult this Attracta review post on Yahoo Voices. |



