Thursday, 28 April 2011

JDBC Hello World program

Register the driver you want:

static{
// register Oracle JDBC driver with DriverManager
Class.forName("oracle.jdbc.driver.OracleDriver");
}

Create a connection object:

//Create a method, in which we will create connection
public void createConnection(){
Connection conn=null;

Now just open the connection:
try{  // get a connection to the database
conn = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:XE",
"scott",
"tiger");

// construct a Statement
Statement stmt = conn.createStatement();

// run query
ResultSet rs = stmt.executeQuery("SELECT 'Hello World' FROM DUAL;");

// iterate through the result set
while (rs.next()) {
System.out.println(rs.getString(1));
}
}
catch(Exception ex){//deal with exception}
 
}//end method 

No comments:

Post a Comment