Modul Pemrograman Desktop
Created by : Team Dosen P.Desktop
MODUL 3 Pemrograman ADO.NET : Connected Environtment TUJUAN : Mahasiswa mampu memahami dan menerapkan penggunaan sintak connected pada database, pada materi ini membahas koneksi secara terus-menerus ke database dengan menggunakan object connection, command dan datareader. Materi : Connection Command DataReader Referensi : Deitel, 2002, Visual Basic .Net How To Program , Prentice Hall, New Jersey.
Jurusan Sistem Informasi, Fakultas Teknologi Industri, UPN “Veteran” JAWA TIMUR
Halaman 34
Modul Pemrograman Desktop
Created by : Team Dosen P.Desktop
ADO.NET ADO.NET component adalah komponen dasar dari membangun aplikasi terintegrasi dengan database pada visual basic.net/ visual studio dan komponen ini menyediakan class yang memungkinkan programmer untuk menghubungkan ke database sebagai penyimpanan, melakukan umpan balik (dari database ke aplikasi), memanipulasi dan memperbaruhi/mengubah data. Pada bab ini, anda mempelajari koneksi dari aplikasi ke database, menjalankan/eksekusi SQL Statement, umpan balik, dan mengubah data di database. ADO kepanjangan dari AxtiveX Data Object, di dalam ADO.NET terdapat komponen data provider, data provider ini yang memungkinkan anda berintegrasi dengan komponen-komponen database, seperti Open DataBase Connectivity (ODBC), Object Linking and Embedding DataBase (OLE DB), SQL Server databases, dan Oracle databases. Contoh penggunaan data provider dalam code : ODBC Imports System.Data.Odbc
OLE DB Imports System.Data.OleDb
SQL SERVER Imports System.Data.SqlClient
ORACLE Imports System.Data.OracleClient
Dalam modul ini anda akan menggunakan data provider miliknya ORACLE karena database yang akan digunakan adalah ORACLE, berikut ini Arsitektur ADO.NET :
Jurusan Sistem Informasi, Fakultas Teknologi Industri, UPN “Veteran” JAWA TIMUR
Halaman 35
Modul Pemrograman Desktop
Created by : Team Dosen P.Desktop
3.1 Connection OracleConnection adalah fasilitas yang dapat digunakan oleh programmer agar dapat berkomunikasi dengan server/database oracle, koneksi dibutuhkan untuk mengirimkan request (command) dan menerima respon (resultset). a. ConnectionString ConnectionString
digunakan
untuk
mendefinisikan
parameter-parameter
yang
dibutuhkan
oleh
OracleConnection untuk membuat koneksi kedalam database ORACLE. Parameter tersebut meliputi :
Data Source=Nama Oracle Instance atau nama database yang anda gunakan atau bisa juga disebut alamat dari server/alamat IP.
Persist Security Info=digunakan untuk apabila anda memasukkan username dan password database secara spesifik, secara default bernilai TRUE.
User ID = digunakan untuk memasukkan username dari database
Contoh penerapan koneksi tanpa melalui tnsnames.ora adalah sebagai berikut : Imports System.Data.OracleClient Public Class Form1 Dim conn As New OracleConnection Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load conn = New OracleConnection("Data Source=orcl;Persist Security Info=True;User ID=hr;Unicode=True; password=hr;") End Sub End Class
Atau anda bisa menggunakan koneksi melalui TNSNAMES.ORA Imports System.Data.OracleClient Public Class Form1 Dim conn As New OracleConnection Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load conn = New OracleConnection("data source=(DESCRIPTION = " & _ "(ADDRESS = (PROTOCOL = TCP)(HOST = agungtama-PC)(PORT = 1521)) " & _ "(CONNECT_DATA = " & _ "(SERVER = DEDICATED) " & _ "(SERVICE_NAME = orcl) " & _ ") " & _ "); user id=hr; password=hr;") conn.Open() End Sub End Class
Alamat TNSNAMES.ORA terdapat pada drive komputer hasil installer Oracle, contohnya adalah sebagai berikut ini = D:\oracle\product\10.2.0\db_1\network\ADMIN\tnsnames.ora Jurusan Sistem Informasi, Fakultas Teknologi Industri, UPN “Veteran” JAWA TIMUR
Halaman 36
Modul Pemrograman Desktop
Created by : Team Dosen P.Desktop
b. Method Open() dan Close() Method open() digunakan untuk membuka koneksi kedalam database, sedangkan method close() digunakan untuk menutup koneksi. Berikut ini implementasi dari method open() dan close() : Imports System.Data.OracleClient Public Class Form1 Dim conn As New OracleConnection Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load conn.Close() conn = New OracleConnection("data source=(DESCRIPTION = " & _ "(ADDRESS = (PROTOCOL = TCP)(HOST = agungtama-PC)(PORT = 1521)) " & _ "(CONNECT_DATA = " & _ "(SERVER = DEDICATED) " & _ "(SERVICE_NAME = orcl) " & _ ") " & _ "); user id=hr; password=hr;") conn.Open() End Sub End Class
Method close digunakan diawal untuk menanggulangi apabila ada lebih dari satu form yang menggunakan koneksi ke database, sehingga ketika setiap form melakukan koneksi maka yang terjadi adalah koneksi akan di Close() terlebih dahulu kemudian di Open() lagi, agar mengurangi crash pada aplikasi. Atau anda bisa menggunakan model koneksi seperti berikut ini : Imports System.Data.OracleClient Public Class Form1 Dim conn As New OracleConnection Sub koneksi() conn.Close() conn = New OracleConnection("data source=(DESCRIPTION = " & _ "(ADDRESS = (PROTOCOL = TCP)(HOST = agungtama-PC)(PORT = 1521)) " & _ "(CONNECT_DATA = " & _ "(SERVER = DEDICATED) " & _ "(SERVICE_NAME = orcl) " & _ ") " & _ "); user id=hr; password=hr;") conn.Open() End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load koneksi() End Sub End Class
Sub koneksi() digunakan untuk mempersingkat code, sehingga tampilan pada form_load akan lebih sedikit, 1 koneksi untuk banyak form. Berikut ini adalah langkah-langkah yang dilakukan untuk koneksi ke database oracle :
Jurusan Sistem Informasi, Fakultas Teknologi Industri, UPN “Veteran” JAWA TIMUR
Halaman 37
Modul Pemrograman Desktop
Created by : Team Dosen P.Desktop
1. Tampilan Form yang siap digunakan
2. Tambahkan refensi untuk database Oracle yang akan dikoneksikan ke Form.
3. Lakukan imports namespace system untuk oracleClient.
4. Buat inisialisasi koneksi
Jurusan Sistem Informasi, Fakultas Teknologi Industri, UPN “Veteran” JAWA TIMUR
Halaman 38
Modul Pemrograman Desktop
Created by : Team Dosen P.Desktop
5. Copy alamat database dengan cara mencari file tnsnames.ora.
6. Buka file tnsnames.ora dengan notepad atau editor teks yang lain.
7. Buat sebuah prosedure yang digunakan sebagai tempat koneksi, beri nama koneksi. Paste alamat yang terdapat pada file tnsnames.ora pada connectionString.
8. Panggil prosedure koneksi pada Form_Load.
Lakukan pengujian kesuksesan koneksi antara form dengan database, dengan cara klik F5 atau tekan tombol Debug
.
Atau anda bisa menggunakan a. langkah 1-4 sama b. langkah berikutnya adalah, arahkan kursor mouse ke server explorer kemudian tekan tombol sehingga muncul dialog box, tekan change pada data source, maka akan muncul dialog box change data source, dan pilih Oracle Database.
Jurusan Sistem Informasi, Fakultas Teknologi Industri, UPN “Veteran” JAWA TIMUR
Halaman 39
Modul Pemrograman Desktop
Created by : Team Dosen P.Desktop
c. setelah itu tekan OK, masukkan server name=instance name, username untuk instance name, dan password untuk instance name pada database oracle, setelah itu tekan tombol Test Connection maka tampilannya adalah sebagai berikut :
d. apabila sudah maka pada server explorer akan muncul data seperti berikut ini.
e. Kemudian klik kanan pada orcl.HR pilih properties, kemudian akan muncul properties box pada sisi kanan, dan copy pada connection string, seperti gambar dibawah ini :
Kemudian masukkan connection string ke dalam OracleConnection dan tambahkan password. Jurusan Sistem Informasi, Fakultas Teknologi Industri, UPN “Veteran” JAWA TIMUR
Halaman 40
Modul Pemrograman Desktop
Created by : Team Dosen P.Desktop
Setting pada database oracle : a.
Masuk ke user hr. Jika user hr masih terkunci, maka lakukan perintah berikut: conn sys/oracle as sysdba; alter user hr identified by hr account unlock; Keterangan:
/oracle adalah password yang ditetapkan saat instalasi oracle. b.
create table dengan nama table tblbarang, tbljenis_barang dan tblsatuan, dengan sintak seperti dibawah ini : table tblbarang : create table TblBarang ( Kode_Barang varchar2(50) not null, Nama_Barang varchar2(50), Jenis varchar2(50), Satuan varchar2(50), Harga_Beli integer, Harga_Jual integer, Stock integer, CONSTRAINT pk_Barang primary key (Kode_Barang) ); table tblsatuan : create table TblSatuan ( No integer, Satuan varchar2(50) ); table tbljenis_barang create table TblJenis_Barang ( No integer, Jenis varchar2(50) );
3.2 Command Object Command digunakan untuk mengirimkan data query ke dalam database, baik query untuk menampilkan data (SELECT) atau query untuk memanipulasi data (INSERT, UPDATE, DELETE), berikut ini contoh penggunaan object command pada oracleCommand.
Jurusan Sistem Informasi, Fakultas Teknologi Industri, UPN “Veteran” JAWA TIMUR
Halaman 41
Modul Pemrograman Desktop
Created by : Team Dosen P.Desktop
Imports System.Data.OracleClient Public Class Form1 Dim conn As New OracleConnection Dim cmd As New OracleCommand Sub koneksi() conn.Close() conn = New OracleConnection("data source=(DESCRIPTION = " & _ "(ADDRESS = (PROTOCOL = TCP)(HOST = agungtama-PC)(PORT = 1521)) " & _ "(CONNECT_DATA = " & _ "(SERVER = DEDICATED) " & _ "(SERVICE_NAME = orcl) " & _ ") " & _ "); user id=hr; password=hr;") conn.Open() End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load koneksi() cmd = New OracleCommand("select * from tblbarang", conn) End Sub End Class
Variable cmd digunakan untuk OracleCommand, sehingga data pada query pada cmd akan dikirimkan ke database untuk dieksekusi dan ditampilkan menggunakan datareader.
3.3 DataReader Method datareader digunakan untuk membaca data (SELECT) dari database setelah dikirimkan oleh object command, method datareader ini berhubungan dengan object OracleCommand. Berikut ini contoh penggunaan code dari object OracleCommand dan Object method datareader : Imports System.Data.OracleClient Public Class Form1 ''''inisialisasi variabel connection, command dan datareader'''''''' Dim conn As New OracleConnection Dim cmd As New OracleCommand Dim dr As OracleDataReader '''''''koneksi'''''''' Dim nomer, satuan As String Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load koneksi() cmd = New OracleCommand("select no, satuan from tblbarang", conn) dr = cmd.ExecuteReader() If dr.HasRows = True Then While dr.Read = True nomer = dr.Item(0) satuan = dr.Item(1) End While dr.Close() End If dr.Close() cmd.Dispose() End Sub End Class
Jurusan Sistem Informasi, Fakultas Teknologi Industri, UPN “Veteran” JAWA TIMUR
Halaman 42
Modul Pemrograman Desktop
Created by : Team Dosen P.Desktop
dr.HasRows=true dapat diartikan bahwa sintak tersebut digunakan untuk mengecek apakah ada data di table yang akan ditampilkan, dr.read=True digunakan untuk membaca data, dr.Item(0) digunakan untuk menampilkan data ke 0 atau kolom no pada object command, dst. method dr.close() untuk menutup sesi dari datareader dalam membaca data, dan cmd.dispose() untuk menutup sesi object command sehingga object command dapat digunakan untuk sesi lainnya tanpa terjadi crash.
3.4 ExecuteNonQuery Method ExecuteNonQuery digunakan untuk mengaktifkan sintak yang dapat memanipulasi data (INSERT, UPDATE, DELETE) dari database setelah dikirimkan oleh object command, Method ExecuteNonQuery ini berhubungan dengan object OracleCommand. Berikut ini contoh penggunaan code dari object OracleCommand dan method ExecuteNonQuery: Imports System.Data.OracleClient Public Class Form1 Dim conn As New OracleConnection Dim cmd As New OracleCommand Dim dr As OracleDataReader '''''''koneksi'''''''' '''''''Form Load'''''''' Private Sub Simpan_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Simpan.Click cmd = New OracleCommand("insert into tblsatuan values('" & no.Text & "','" & dataSatuan.Text & "')", conn) cmd.ExecuteNonQuery() End Sub End Class
Atau Imports System.Data.OracleClient Public Class Form1 Dim conn As New OracleConnection Dim cmd As New OracleCommand Dim dr As OracleDataReader '''''''koneksi'''''''' '''''''Form Load'''''''' Private Sub Simpan_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Simpan.Click cmd = New OracleCommand("insert into tblsatuan(no, satuan) values('" & no.Text & "','" & dataSatuan.Text & "')", conn) cmd.ExecuteNonQuery() End Sub End Class
Latihan 1. Buatlah tampilan seperti berikut ini :
Jurusan Sistem Informasi, Fakultas Teknologi Industri, UPN “Veteran” JAWA TIMUR
Halaman 43
Modul Pemrograman Desktop
Created by : Team Dosen P.Desktop
1
1 2
B
2
3
3
A
4
1
3
2
4
C
D
Keterangan Gambar : Blok A : untuk object Textbox yang ke 1 Setting Properties => Name = kdBrg; TabIndex = 0; Font = 10Pt; untuk object Textbox yang ke 2 Setting Properties => Name = nmBrg; TabIndex = 1; Font = 10Pt; untuk object Textbox yang ke 3 Setting Properties => Name = jns; TabIndex = 2; Font = 10Pt; untuk object Textbox yang ke 1 Setting Properties => Name = satuan; TabIndex = 3; Font = 10Pt; Blok B : untuk object NumericUpDown yang ke 1 Setting Properties => Name = HB; TabIndex = 4; Font = 10Pt; maximum=10000000; untuk object NumericUpDown yang ke 2 Setting Properties => Name = HJ; TabIndex = 5; Font = 10Pt; maximum=10000000; untuk object NumericUpDown yang ke 3 Setting Properties => Name = stk; TabIndex = 6; Font = 10Pt; maximum=10000; Blok C : untuk object Button yang ke 1 Setting Properties => Name = btnBr; TabIndex = 7; Font = 10Pt; Text=Baru; untuk object Button yang ke 2 Setting Properties => Name = btnSimpan; TabIndex = 8; Font = 10Pt; Text=Simpan; untuk object Button yang ke 3 Setting Properties => Name = btnUbah; TabIndex =9; Font = 10Pt; Text=Ubah; untuk object Button yang ke 4 Setting Properties => Name = btnHps; TabIndex = 10; Font = 10Pt; Text=Hapus; Blok D : untuk object Listview Setting Properties => Name = ListView1; TabIndex = 11; Font = 10Pt; View = Details; FullRowSelect = True; Columns : Columns 1 : Text = Kode Barang; width = 120; Columns 5 : Text = Beli; width = 100; Columns 2 : Text = Nama Barang; width = 220; Columns 6 : Text = Jual; width = 100; Columns 3 : Text = Jenis; width = 100; Columns 7 : Text = Stok; width = 100; Columns 4 : Text = Satuan; width = 100;
Jurusan Sistem Informasi, Fakultas Teknologi Industri, UPN “Veteran” JAWA TIMUR
Halaman 44
Modul Pemrograman Desktop
Created by : Team Dosen P.Desktop
2. Lakukan Imports, dan add reference untuk data oracle (sintak import dan add reference seperti diatas) 3. lakukan inisialisasi variable untuk connection, command dan datareader. 4. buat sub untuk koneksi. 5. dalam form load, panggil sub koneksi dengan cara koneksi() 6. berikut ini tampilan imports, inisialisasi, sub koneksi dan penggunaan koneksi dalam form load.
7. dalam form_load dibawah koneksi()masukkan sintak untuk menampilkan data pada listview, seperti berikut ini : Private Sub modul3_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load koneksi() ListView1.Items.Clear() cmd = New OracleCommand("SELECT kode_barang, nama_barang, jenis, satuan, harga_beli, harga_jual, stock from tblbarang ", conn) dr = cmd.ExecuteReader() If dr.HasRows Then While dr.Read() ListView1.Items.Add(dr.Item(0)) ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(dr.Item(1)) ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(dr.Item(2)) ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(dr.Item(3)) ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(dr.Item(4)) ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(dr.Item(5)) ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(dr.Item(6)) End While dr.Close() End If dr.Close() cmd.Dispose() End Sub
8. Double klik pada button baru di design form, button ini berfungsi untuk membersihkan inputan pada textbox dan NumericUpDown.
Jurusan Sistem Informasi, Fakultas Teknologi Industri, UPN “Veteran” JAWA TIMUR
Halaman 45
Modul Pemrograman Desktop
Created by : Team Dosen P.Desktop
Dim ctr As Control Private Sub btnBr_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBr.Click '''''sintak untuk membersihkan textbox dan NumericUpDown For Each ctr In Me.Controls If TypeOf ctr Is TextBox Then ctr.Text = "" End If If TypeOf ctr Is NumericUpDown Then ctr.Text = "0" End If Next End Sub
9. Double klik pada button simpan di design form, button ini berfungsi untuk memasukkan data ke table tblbarang di Database. Private Sub btnSimpan_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSimpan.Click '''''digunakan untuk sintak DML, untuk button ini digunakan untuk insert data cmd = New OracleCommand("insert into tblbarang values ('" & kdBrg.Text & "','" & nmBrg.Text & "'," & _ "'" & jns.Text & "','" & satuan.Text & "'," & HB.Value & "," & HJ.Value & "," & stk.Value & ")", conn) cmd.ExecuteNonQuery() '''' digunakan untuk menampilkan data ke listview setelah memasukkan data ListView1.Items.Clear() cmd = New OracleCommand("SELECT kode_barang, nama_barang, jenis, satuan, harga_beli, harga_jual, stock from tblbarang", conn) dr = cmd.ExecuteReader() If dr.HasRows Then While dr.Read() ListView1.Items.Add(dr.Item(0)) ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(dr.Item(1)) ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(dr.Item(2)) ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(dr.Item(3)) ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(dr.Item(4)) ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(dr.Item(5)) ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(dr.Item(6)) End While dr.Close() End If dr.Close() cmd.Dispose() End Sub
Jurusan Sistem Informasi, Fakultas Teknologi Industri, UPN “Veteran” JAWA TIMUR
Halaman 46
Modul Pemrograman Desktop
Created by : Team Dosen P.Desktop
10. Double klik pada button ubah di design form, button ini berfungsi untuk mengubah data ke table tblbarang di Database berdasarkan primary key di table. '''''digunakan untuk sintak DML, untuk button ini digunakan untuk update data cmd = New OracleCommand("update tblbarang set nama_barang='" & nmBrg.Text & "'," & _ "jenis='" & jns.Text & "',satuan='" & satuan.Text & "',harga_beli=" & HB.Value & ",harga_jual=" & HJ.Value & ",stock=" & stk.Value & " where kode_barang='" & kdBrg.Text & "'", conn) cmd.ExecuteNonQuery() '''' digunakan untuk menampilkan data ke listview setelah mengubah data ListView1.Items.Clear() cmd = New OracleCommand("SELECT kode_barang, nama_barang, jenis, satuan, harga_beli, harga_jual, stock from tblbarang", conn) dr = cmd.ExecuteReader() If dr.HasRows Then While dr.Read() ListView1.Items.Add(dr.Item(0)) ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(dr.Item(1)) ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(dr.Item(2)) ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(dr.Item(3)) ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(dr.Item(4)) ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(dr.Item(5)) ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(dr.Item(6)) End While dr.Close() End If dr.Close() cmd.Dispose() End Sub
11. Double klik pada button hapus di design form, button ini berfungsi untuk menghapus data ke table tblbarang di Database berdasarkan primary key di table.
Jurusan Sistem Informasi, Fakultas Teknologi Industri, UPN “Veteran” JAWA TIMUR
Halaman 47
Modul Pemrograman Desktop
Created by : Team Dosen P.Desktop
Private Sub btnHps_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnHps.Click '''''digunakan untuk sintak DML, untuk button ini digunakan untuk delete data cmd = New OracleCommand("delete tblbarang where kode_barang='" & kdBrg.Text & "'", conn) cmd.ExecuteNonQuery() '''' digunakan untuk menampilkan data ke listview setelah menghapus data ListView1.Items.Clear() cmd = New OracleCommand("SELECT kode_barang, nama_barang, jenis, satuan, harga_beli, harga_jual, stock from tblbarang", conn) dr = cmd.ExecuteReader() If dr.HasRows Then While dr.Read() ListView1.Items.Add(dr.Item(0)) ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(dr.Item(1)) ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(dr.Item(2)) ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(dr.Item(3)) ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(dr.Item(4)) ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(dr.Item(5)) ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(dr.Item(6)) End While dr.Close() End If dr.Close() cmd.Dispose() End Sub
Jurusan Sistem Informasi, Fakultas Teknologi Industri, UPN “Veteran” JAWA TIMUR
Halaman 48
Modul Pemrograman Desktop
Created by : Team Dosen P.Desktop
PEKERJAAN RUMAH (PR) & CATATAN
Jurusan Sistem Informasi, Fakultas Teknologi Industri, UPN “Veteran” JAWA TIMUR
Halaman 49
Modul Pemrograman Desktop
Created by : Team Dosen P.Desktop
Jurusan Sistem Informasi, Fakultas Teknologi Industri, UPN “Veteran” JAWA TIMUR
Halaman 50