• Tidak ada hasil yang ditemukan

OOP LANJUT PEMROSESAN DATABASE MENGGUNAKAN JDBC. Niko Ibrahim, MIT Universitas Kristen Maranatha

N/A
N/A
Protected

Academic year: 2021

Membagikan "OOP LANJUT PEMROSESAN DATABASE MENGGUNAKAN JDBC. Niko Ibrahim, MIT Universitas Kristen Maranatha"

Copied!
28
0
0

Teks penuh

(1)

OOP LANJUT

PEMROSESAN DATABASE

MENGGUNAKAN JDBC

Niko Ibrahim, MIT

(2)

Tujuan

Memahami Koneksi dan Pemrosesan Basis Data di Java

Memahami JDBC

(3)

Materi

 Pengenalan library JDBC

 Diagram pengaksesan database melalui JDBC  Step-by-step Setting JDBC untuk MySQL

 Cara Melakukan Query (SELECT)  Cara Memproses Hasil Query  Cara Update/Insert/Delete

(4)

1

st

Thing 1

st

: Siapkan MySQL

 Jalankan MySQL server + Apache server (melalui XAMPP Control Panel)  Masuk ke phpMyAdmin: http://localhost/phpmyadmin/

 Di dalam phpMyAdmin, import the “movieSQL.sql” script  Browse table “movie”, yang isinya adalah sbb:

(5)

Pengenalan: JDBC Library

 JDBC — Java Database Connectivity — adalah suatu feature di Java yang

memungkinkan kita untuk melakukan:

Koneksi ke hampir semua sistem RDBMS yang ada saat ini,  Eksekusi perintah SQL, dan

Memproses hasil perintah SQL melalui program Java

 Library JDBC terdiri atas class-class yang berguna untuk setiap tasks di

dalam pemrosesan database, misalnya class untuk:

 Membuat koneksi ke database

 Membuat statement menggunakan SQL

 Mengeksekusi query SQL (statement) di dalam database  Menampilkan records yang dihasilkan

(6)

Bagaimana program Java mengakses

database melalui JDBC?

Program JDBC driver sybase driver oracle driver mysql SYBASE ORACLE MYSQL

(7)

JDBC Driver:

Apa itu & Bagaimana mendapatkannya?

First Thing First: Setting Up a Driver

 Sebelum Anda dapat menulis program Java yang mengakses database

melalui JDBC, pertama-tama Anda harus meng-instal sebuah Driver yang menghubungkan class-class di dalam Java’s database API dengan

database yang akan digunakan.

Untuk setiap database yang ada di pasaran saat ini, hampir

semuanya memiliki driver JDBC-nya.

Biasanya driver ini dapat didownload secara gratis melalui

website perusahaan database masing-masing.

(8)

Setting up MySQL JDBC Driver

Database connector is a driver provided by your database vendor.

Database connectors are designed to work exclusively with a specific type of database.

 You have to obtain the JDBC connector for the database you’re using from

the company that makes the database server you’re using.

 For example, you can get a JDBC connector for MySQL from the MySQL

Web site at www.mysql.com .

(9)

Step-by-step for: MySQL JDBC driver

Download Driver dan Setting Environment

1. Download driver JBDC MySQL dari website berikut:

www.mysql.com/products/connector lalu unzip file tsb. Driver JDBC untuk MySQL dinamakan: MySQL Connector/J.

Setelah Anda mendownloadnya, unzip file tsb ke suatu folder, misalnya: “c:\MySQL”

2.

Tambahkan file driver yang berekstensi “.jar” ke dalam

variabel “ClassPath”

Misalnya *):

c:\mysql\mysql-connector-java-3.1.10-bin.jar

atau

C:\mysql\mysql-connector-java-5.0.7\mysql-connector-java-5.0.7-bin.jar  *) tergantung lokasi dan versi driver yang digunakan

 That’s all you have to do. You can now connect to MySQL from a Java

(10)

6 Langkah Koneksi & Akses Database

1.

Memanggil Driver JDBC

2.

Mendefinisikan URL untuk Koneksi Basis Data &

Melakukan Koneksi tsb

3.

Membuat Objek Statement

4.

Melakukan Query/Update

5.

Memproses Hasil

(11)

1. Memanggil Driver JDBC

 Sebelum kita dapat menggunakan JDBC untuk mengakses database SQL,

kita harus melakukan koneksi terlebih dahulu.

 Langkah pertama dalam melakukan koneksi adalah: registrasi driver  Caranya adalah dengan menggunakan method “forName” dari kelas

“Class”

 Misalnya untuk meregistrasi connector MySQL, gunakan perintah berikut:

Class.forName("com.mysql.jdbc.Driver");

 Note that the forName method throws ClassNotFoundException, so

you have to enclose this statement in a try/catch block that catches

ClassNotFoundException. try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException){ // error handling }

(12)

2. Mendefinisikan URL dan

Melakukan Koneksi

 Setelah melalukan registrasi driver class tsb, kita dapat memanggil method

getConnection untuk membuka koneksi ke database.

 Method ini membutuhkan 3 parameter String:the database URL, the user name, and a

password.

 Contoh:

String url = "jdbc:mysql://localhost/movies"; String user = "root";

String pw = "";

Connection conn = DriverManager.getConnection(url, user, pw);

 Note that the getConnection method throws SQLException, so you need to

enclose it in a try/catch block statement that catches this exception.

 Note: You can find these classes — and the other classes for working with SQL

databases — in the java.sql package. As a result, you have to include an

import statement that specifies this package in any program that uses JDBC.

(13)

3. Membuat Objek Statement

 Kita memerlukan objek Statement untuk melakukan query dan objek ini

dapat dibuat dari objek Connection.

 Sintaks kode:

Statement st = conn.createStatement();

Statement: The Statement interface contains the methods necessary to send

statements to the database for execution and return the results.

 Use the executeQuery method to execute a select statement, or

 Use the executeUpdate method to execute an insert, update, or delete statement.

(14)

Putting it all together (Step 1 to 3)

 Berikut ini adalah sebuah method yang me-return objek Connection

yang berfungsi sebagai penghubung ke database MySQL: private static Connection getConnection(){

Connection con = null;

try{

Class.forName("com.mysql.jdbc.Driver ");

String url = "jdbc:mysql://localhost/movies"; String user = "root";

String pw = " ";

con = DriverManager.getConnection(url, user, pw); }

catch (ClassNotFoundException e){

System.out.println(e.getMessage()); System.exit(0);

}

catch (SQLException e){

System.out.println(e.getMessage()); System.exit(0);

}

return con; }

(15)

4. Melakukan Query atau Update

 Setelah kita memiliki objek Statement, kita dapat menggunakannya untuk

mengirimkan query dan mengeksekusinya dengan method executeQuery yang

menghasilkan objek bertipe ResultSet.

ResultSet: The ResultSet interface represents rows returned from a query.

It provides methods you can use to move from row to row and to get the data for a column.

 Contoh:

String query = "SELECT id, title FROM movie";

ResultSet rs = st.executeQuery(query);

 Note: Apabila ingin melakukan update/insert/delete, gunakan

(16)

5a. Memproses Hasil Query

Untuk memproses hasil query, kita gunakan objek

resultSet

karena hasil query disimpan dalam objek ini.

Method yang sering digunakan:

next

dan

getString

Contoh pemrosesan hasil query:

while (rs.next()){

System.out.println(rs.getString(1) + " " +

rs.getString(2)); }

Kode di atas akan menampilkan

semua baris hasil query

yang

(17)

Memproses hasil query (cont.)

Navigating through the result set

 The ResultSet object returned by the executeQuery statement contains

all the rows that are retrieved by the select statement.

 You can only access one of those rows at a time.

 You can use the methods shown in the table to move the cursor through a result

set.

 For example, the following snippet shows how you can structure code that

processes each row in a result set: while(rows.next()) {

// process the current row

}

 All you have to do is replace the comment with statements that retrieve data from

the result set and process it, as described in the next section.

Method Description

void close() Closes the result set

void last() Moves the cursor to the last row

int getRow() Gets the current row number

(18)

Memproses hasil query (cont.)

Example: Navigating the result set

// Already done:

// ResultSet rs = st.executeQuery(select);

try {

while (rs.next()){

String title = movies.getString("Title"); int year = movies.getInt("Year");

double price = movies.getDouble("Price");

String msg = title + " " + year + " " + price; System.out.println(msg);

} }

catch (SQLException e){

System.out.println(e.getMessage()); }

(19)

Memproses hasil query (cont.)

Getting data from the result set

 The following table lists the methods of the ResultSet interface you can use to

retrieve data from the current row.

 As you can see, each of these methods comes in two versions:

 One specifies the column by name, the other by index number.

 If you know the index number, using it to access the column values is more efficient than using

the column names.

Method Description

boolean getBoolean(String columnName) Gets the value of the specified column as a boolean

boolean getBoolean(int columnIndex) Gets the value of the specified column as a boolean

Date getDate(String columnName) Gets the value of the specified column as a Date

Date getDate(int columnIndex) Gets the value of the specified column as a Date

double getDouble(String columnName) Gets the value of the specified column as a double

double getDouble(int columnIndex) Gets the value of the specified column as a double

int getInt(String columnName) Gets the value of the specified column as a int

int getInt(int columnIndex) Gets the value of the specified column as a int

String getString(String columnName) Gets the value of the specified column as a String

(20)

5b. Untuk Proses Update/Insert/Delete

Setelah mengerti bagaimana menampilkan data, maka kita

perlu mengerti bagaimana

menambah/menghapus/mengupdate

data ke tabel.

Untuk melakukan hal tersebut, kita menggunakan method

executeUpdate("perintah sql untuk insert / update / delete");

Method tersebut akan menghasilkan

nilai integer

yang

merupakan

jumlah baris

yang dipengaruhi oleh proses update

tersebut.

int i = st.executeUpdate(

(21)

5b. Untuk Proses Insert/Update/Delete

(cont...)

 Untuk proses updating tabel, kita bisa juga menggunakan objek PreparedStatement:  Untuk mengeksekusi PreparedStatement, kita gunakan method executeUpdate()  Berikut contoh penggunaannya:

PreparedStatement st =

conn.prepareStatement ("INSERT INTO movie VALUES (?,?,?)"); st.setString(1, "Passion of The Christ");

st.setInt(2, 2004); st.setDouble(3, 22.5); int i = st.executeUpdate(); .... .... st.close();

(22)

6. Menutup Koneksi

 Sebelum menutup koneksi basis data, kita juga perlu melepaskan objek

ResultSet yang ada dengan kode berikut: st.close();

 Untuk menutup koneksi ke basis data, kita tuliskan sbb:

(23)

1.

ListMovies.java: aplikasi console

2.

Swing & JDBC: Address Book

3.

NetBeans & DB tutorial: Contact Application

(24)

Exercise 1

:

ListMovies.java

1

st

Thing 1

st

: Siapkan MySQL

 Jalankan MySQL server + Apache server (melalui XAMPP Control Panel)  Masuk ke phpMyAdmin: http://localhost/phpmyadmin/

 Di dalam phpMyAdmin, import the “movieSQL.sql” script  Browse table “movie”, yang isinya adalah sbb:

(25)

Exercise 1

:

ListMovies.java

Open & Run Console Application: “ListMovies.java”

 See the full code in “ListMovies.java”

 When you run the code, the following appears in the console:

1946: It’s a Wonderful Life ($16.45)

1965: The Great Race ($14.25)

1974: Young Frankenstein ($18.65)

1975: The Return of the Pink Panther ($13.15) 1977: Star Wars ($19.75)

1987: The Princess Bride ($18.65) 1989: Glory ($16.45)

1995: Apollo 13 ($20.85) 1997: The Game ($16.45)

(26)

Exercise 2: Swing & JDBC

Address book (Lihat file PDF yang diberikan)

 Tutorial membuat address book menggunakan Swing dan JDBC

 Buat project “java application” baru

 Nama Project: AddressBookDemoDB  Uncheck “create main class”

 Buat database & user:

 Buat user baru di MYSQL: (apabila perlu)

 Userid: niko

 Password: niko

 Jalankan script yan berfungsi:

 membuat MySQL database: addressbook

 Membuat Table: Person

create table Person ( id integer, name varchar(30), address varchar(30), phone integer, email varchar(50) )

 Ada 3 files berikut di dalam project:

 PersonInfo: class JavaBeans berisi atribut dan method untuk Person

 PersonDAO: class yang menyediakan pengaksesan database untuk objek Person

(27)

A final word for JDBC

 Berikut cuplikan dokumentasi dari MySQL Connector/J:

“Although JDBC is useful by itself, we would hope that if you are not familiar with JDBC that after reading the first few sections of this manual, that you would avoid using naked JDBC for all but the most trivial problems and

consider using one of the popular persistence frameworks such as Hibernate, Spring's JDBC templates or Ibatis SQL Maps to do the majority of repetitive work and heavier lifting that is sometimes required with JDBC.”

 Produk Persistence Framework yang paling populer digunakan saat ini

adalah Hibernate dan Oracle TopLink.

 Framework ini dinamakan JPA (Java Persisitence API) yang merupakan

(28)

That’s all for today, folks!

Selamat, Anda telah menyelesaikan sebuah topik penting di

Java yaitu pengaksesan Database.

Setelah mengikuti kuliah ini, Anda diharapkan mampu:

 Memahami penggunaan JDBC  Melakukan koneksi ke MySQL  Melakukan pemrosesan database

 Mengetahui framework penyimpanan data (persistence) yang lebih

Referensi

Dokumen terkait

6 (i) Kursus yang dipohon untuk pemindahan kredit mempunyai pertindihan sekurang-kurangnya 75% dengan kursus yang ditawarkan di Universiti ini; (ii) Gred atau mata gred

Berdasarkan uraian yang telah dijelaskan sebelumnya, maka dapat disimpulkan bahwa bahan ajar berupa buku siswa menggunakan konteks bahan bakar minyak dengan pendekatan

Alasan masuk S1 Pendidikan Bahasa Inggris FKIP-UT karena tidak perlu meninggalkan tugas/fleksibel merupakan pilihan terbanyak yang di pilih oleh responden

Kelompok yang diberi pakan bungkil kelapa menghasilkan rata-rata jumlah kista yang paling sedikit tetapi mempunyai kista dengan ukuran diameter paling besar dan sebaliknya

Pada masa akhir usia sekolah 10-12 tahun atau pra remaja,anak- anak terlihat semakin mahir menggunakan logikanya contohnya dari kemahiran dalam masalah hitung

komponen public key system (PKS) diantaranya certification authority (CA) merupakan sebuah body/entity yang memberikan dan mengelola sertifikat digital yang dibutuhkan

Modul ke: Fakultas Program Studi Dasar-dasar Metode Penelitian • Kontrak Perkuliahan • Filsafat Ilmu • Logika Ilmiah.. • Sejarah &

Indra Tedjakumala, diketahui bahwa jumlah gigi minimum tergantung dari sudut jumlah gigi minimum tergantung dari sudut tegangan [.. tegangan [ 