Creating Java Prog Using JDBC PDF
Creating Java Prog Using JDBC PDF
• Import the packages: Requires that you include the packages containing the
JDBC classes needed for database programming. Most often, using import
java.sql.* will suffice.
• Register the JDBC driver: Requires that you initialize a driver so you can
open a communication channel with the database.
• Execute a query: Requires using an object of type Statement for building and
submitting an SQL statement to the database.
• Extract data from result set: Requires that you use the
appropriate ResultSet.getXXX() method to retrieve the data from the result
set.
Sample Code
This sample example can serve as a templatewhen you need to create
your own JDBC application in the future.
This sample code has been written based on the environment and
database setup done in the previous chapter.
import java.sql.*;
try{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
int id = rs.getInt("id");
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end try
System.out.println("Goodbye!");
}//end main
}//end FirstExample
C:\>javac FirstExample.java
C:\>
C:\>java FirstExample
Connecting to database...
Creating statement...
C:\>