JDBC
: 04 - JDBC PreparedStatement Insert Example
*
PreparedStatement Interface is a sub interface of the Statement
Interface.
 *
PreparedStatement is used to execute parameterized query.
 *
The performance of the application will be faster since query is
compiled only once.
import
java.sql.Connection;
import
java.sql.Date;
import
java.sql.DriverManager;
import
java.sql.PreparedStatement;
import
java.sql.SQLException;
/**
 *
@author
sanjeeva
 *
PreparedStatement Interface is a sub interface of the Statement
Interface.
 *
PreparedStatement is used to execute parameterized query.
 *
 *
The performance of the application will be faster since query is
compiled only once.
 *
 *
===================
 
CREATE TABLE IF
NOT EXISTS `DBUSER` (
  
`USER_ID`
int(10) NOT NULL,
  
`USERNAME`
varchar(20) NOT NULL,
  
`CREATED_BY`
varchar(20) NOT NULL,
  
`CREATED_DATE`
date NOT NULL,
  
PRIMARY KEY
(`USER_ID`)
  )
 
==================== 
 */
public
class
PreparedStatementInsertExample {
     Connection
connection
= null;
     /**
     * @param
args
     */
     public
static
void
main(String[] args) {
          PreparedStatementInsertExample
insertexample = new
PreparedStatementInsertExample();
           insertexample.doExecute();
     }
     private
void
doExecute(){
           PreparedStatement
prstatement = null;
            Date
date = new
Date(new
java.util.Date().getTime());
           String
insertSQL = "INSERT INTO DBUSER
VALUES(?,?,?,?)"; 
            try
{
                   Class.forName("com.mysql.jdbc.Driver");
                 String
username = "root";
                 String password = "res13pg";
        
                   connection
= DriverManager
.getConnection("jdbc:mysql://localhost:3306/myworkspace",username,password);
                 if(null
!= connection){
                          prstatement
= connection.prepareStatement(insertSQL);
                          prstatement.setInt(1,
104);
                          prstatement.setString(2,
"Chandima");
                          prstatement.setString(3,
"System");
                          prstatement.setDate(4,
date);
                          int
i = prstatement.executeUpdate();
                          System.out.println("
" + i + "
Record Inserted");
                 }
            }
catch
(ClassNotFoundException e) {
                 e.printStackTrace();
           }
catch
(SQLException e) {
                 e.printStackTrace();
           }
finally
{
                   if
(null
!= connection){
                        try
{
                              connection.close();
                     }
catch
(SQLException e) {
                                //
TODO
Auto-generated catch block
                            e.printStackTrace();
                     }
                 }
           }
     }
}
