Home > Java > JDBC PreparedStatement

JDBC PreparedStatement

Selain menggunakan Statement untuk mengeksekusi perintah SQL, kita juga dapat menggunakan PreparedStatement. Berikut ini merupakan contoh penggunakan PreparedStatement untuk melakukan perintah SQL ( Insert ).

1. GetConnection.Java

/**
*
* @author Kukuh Utama
*/

import java.sql.SQLException;
import java.sql.DriverManager;
import java.sql.Connection;
import java.util.logging.Level;
import java.util.logging.Logger;

public class GetConnection {
private final String db_driver = "oracle.jdbc.Driver";
private final String db_connection = "jdbc:mysql://localhost:3306/db_perpustakaan";
private final String db_user = "root";
private final String db_password = "";
Connection conn;

public GetConnection(){
try{
Class.forName(db_driver);

} catch(ClassNotFoundException ex){
ex.getMessage();
}
}

public Connection getDBConnection(){
try {
conn = DriverManager.getConnection(db_connection, db_user, db_password);
} catch (SQLException ex) {
System.out.println("Connection Failed! Check output console");
ex.getMessage();
}
return conn;

}

}

2.JDBCStatement

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
*
* @author Kukuh Utama
*/
public class JDBCStatement {

/**
* @param args the command line arguments
*/
public static void main(String[] args) throws SQLException {

GetConnection setConn = new GetConnection();
Connection conn;

conn = setConn.getDBConnection();

String SQLInsert ="INSERT INTO tbl_buku(id_buku, judul_buku, pengarang, penerbit, jumlah) values (?, ?, ?, ?, ?)";
PreparedStatement prStatement;

prStatement = conn.prepareStatement(SQLInsert);
prStatement.setInt(1, 100);
prStatement.setString(2, "Sejarah Dunia");
prStatement.setString(3, "Maria Ano");
prStatement.setString(4, "Erlangga");
prStatement.setInt(5,100);

prStatement.executeUpdate();

if( prStatement != null){
prStatement.close();
}
if(conn != null){
conn.close();
}

}
}

 

Beberapa benefit dengan menggunakan PreparedStatement.

1. PreparedStatement lebih cepat daripada Statement.

2. PreparedStatement lebih dinamis dengan query berparameter

3. PreparedStatement mencegah SQL Injection attacks pada Java

Semoga Bermanfaat.🙂

Referensi : Dari Berbagai Sumber.

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: