Review should be made, as an example, to the following code for writing data from within Java to a database table:
//STEP 1. Import required packages
import java.sql.*;
public class JDBCExampleWrite {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.oracle.jdbc.Driver";
static final String DB_URL = "jdbc:oracle://localhost/CourseSelection";
// Username and Password
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.oracle.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to an oracle database...");
conn = DriverManager.getConnection(OracleURL, USER, PASS);
System.out.println("Connected to database successfully...");
//STEP 4: Execute a query
System.out.println("Inserting records into the CourseSelection table...");
stmt = conn.createStatement();
String sql = "INSERT INTO CourseSelection " + "VALUES (6660, 'Drake', 'Thane', 18)"; stmt.executeUpdate(sql);
sql = "INSERT INTO CourseSelection "+ "VALUES (6630, 'Peyton', 'Willem', 25)"; stmt.executeUpdate(sql);
sql = "INSERT INTO CourseSelection " + "VALUES (6640, 'Kim', 'Grace', 30)";
stmt.executeUpdate(sql); sql = "INSERT INTO CourseSelection " + "VALUES(6662, 'Evers', 'Steph', 28)"; stmt.executeUpdate(sql);
System.out.println("Inserted data into the table...");
}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(stmt!=null)
conn.close();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Success!");
}//end main
}//end JDBCExampleWrite
: