0% menganggap dokumen ini bermanfaat (0 suara)
13 tayangan15 halaman

Pertemuan XV Database Python

Diunggah oleh

nuris candra
Hak Cipta
© © All Rights Reserved
Kami menangani hak cipta konten dengan serius. Jika Anda merasa konten ini milik Anda, ajukan klaim di sini.
Format Tersedia
Unduh sebagai PPTX, PDF, TXT atau baca online di Scribd
0% menganggap dokumen ini bermanfaat (0 suara)
13 tayangan15 halaman

Pertemuan XV Database Python

Diunggah oleh

nuris candra
Hak Cipta
© © All Rights Reserved
Kami menangani hak cipta konten dengan serius. Jika Anda merasa konten ini milik Anda, ajukan klaim di sini.
Format Tersedia
Unduh sebagai PPTX, PDF, TXT atau baca online di Scribd
Anda di halaman 1/ 15

Database Python

Pertemuan XV
Materi
• Install PyMySql
• Database Connection
• Create Table
• Insert

Teknik Informatika - Universitas Ka


• Read

huripan Kediri
2
Akses Database Python
• Standar Interface Python untuk database adalah Python DB-API. Kebanyakan
Interface database Python mematuhi standar ini.
• Database yang didukung API Database Python :
• GadFly
• mSQL
• MySQL
• PostgreSQL

Teknik Informatika - Universitas Ka


• Microsoft SQL Server 2000
• Informix
• Interbase
• Oracle

huripan Kediri
• Sybase
• SQLite
• Mulai Python 3 Modul MySQLdb tidak kompatibel dengan. Sebagai gantinya, kita
akan menggunakan modul PyMySQL.
3
Apa itu PyMySQL ?
• PyMySQL adalah sebuah antarmuka untuk menghubungkan ke server
database MySQL dari Python. Ini mengimplementasikan API Database
Python v2.0 dan berisi perpustakaan klien MySQL murni-Python. Tujuan
PyMySQL adalah penggantian drop-in untuk MySQLdb. Anda dapat melihat
dokumentasi lengkap penggunaan PyMySQL di
https://pymysql.readthedocs.io/en/latest/.

Teknik Informatika - Universitas Ka


huripan Kediri
4
Cara Instal PyMySQL
• Sebelum melanjutkan, pastikan Anda telah menginstal PyMySQL di
komputer Anda. Cukup ketik berikut ini di skrip Python Anda dan jalankan.
• import pymysql.cursors
• Jika menghasilkan hasil berikut, berarti modul MySQLdb tidak terpasang:
• Traceback (most recent call last): File "test.py", line 3, in Import
PyMySQL ImportError: No module named PyMySQL
• Untuk menginstal modul PyMySQL silahkan gunakan command/perintah

Teknik Informatika - Universitas Ka


berikut di command prompt:
• python -m pip install PyMySQL
• Note :
Apabila ada kesulitan instalasi bisa mengikuti klik link tutorial dibawah ini

huripan Kediri
https://www.youtube.com/watch?v=n_8aA4r6V-o

5
Database Connection
• Sebelum terhubung ke database MySQL, pastikan beberapa hal dibawah ini :
• Anda telah membuat database TESTDB.
• Anda telah membuat tabel EMPLOYEE di TESTDB.
• Tabel ini memiliki bidang FIRST_NAME, LAST_NAME, AGE, SEX, dan INCOME.
• User ID “testuser” dan password “test123” diatur untuk mengakses TESTDB.
• Python modul PyMySQL terinstal dengan benar pada mesin Anda.
• Anda telah melalui tutorial MySQL untuk memahami Dasar-Dasar MySQL
• Berikut ini adalah contoh koneksi dengan database MySQL “TESTDB”

Teknik Informatika - Universitas Ka


import pymysql.cursors # execute SQL query using execute() method.
cursor.execute("SELECT VERSION()")
# Open database connection
db = # Fetch a single row using fetchone()

huripan Kediri
pymysql.connect("localhost","testuser","test method.
123","TESTDB" ) data = cursor.fetchone()

# prepare a cursor object using cursor() print ("Database version : %s " % data) 6
method
cursor = db.cursor() # disconnect from server
db.close()
Membuat Tabel Database
import pymysql.cursors

# Open database connection


db = pymysql.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method


cursor = db.cursor()

# Drop table if it already exist using execute() method.

Teknik Informatika - Universitas Ka


cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")

# Create table as per requirement


sql = """CREATE TABLE EMPLOYEE (
FIRST_NAME CHAR(20) NOT NULL,

huripan Kediri
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
INCOME FLOAT )"""
7
cursor.execute(sql)

# disconnect from server


Operasi Insert
• Contoh berikut, mengeksekusi pernyataan SQL INSERT untuk membuat catatan di
tabel EMPLOYEE
import pymysql.cursors

# Open database connection


db = pymysql.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method


cursor = db.cursor()

Teknik Informatika - Universitas Ka


# Prepare SQL query to INSERT a record into the database.
sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
LAST_NAME, AGE, SEX, INCOME)
VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""
try:

huripan Kediri
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error 8
db.rollback()

# disconnect from server


Operasi Insert
• Contoh di atas bisa dituliskan sebagai berikut untuk membuat query SQL secara
dinamis
import pymysql.cursors

# Open database connection


db = pymysql.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method


cursor = db.cursor()

Teknik Informatika - Universitas Ka


# Prepare SQL query to INSERT a record into the database.
sql = "INSERT INTO EMPLOYEE(FIRST_NAME, \
LAST_NAME, AGE, SEX, INCOME) \
VALUES ('%s', '%s', '%d', '%c', '%d' )" % \
('Mac', 'Mohan', 20, 'M', 2000)
try:

huripan Kediri
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error 9
db.rollback()

# disconnect from server


Read Operation
• READ Operation pada database apapun berarti mengambil beberapa
informasi berguna dari database.
• Setelah koneksi database terbentuk, Anda siap untuk membuat query ke
dalam database ini. Anda bisa menggunakan metode fetchone() untuk
mengambil satu record atau fetchall() metode untuk mengambil beberapa
nilai dari tabel database.
• Fetchone () - Ini mengambil baris berikut dari kumpulan hasil query. Set hasil
adalah objek yang dikembalikan saat objek kursor digunakan untuk query

Teknik Informatika - Universitas Ka


tabel.
• Fetchall () - Ini menjemput semua baris dalam kumpulan hasil. Jika beberapa
baris telah diekstraksi dari himpunan hasil, maka akan diambil baris yang
tersisa dari kumpulan hasil.

huripan Kediri
• Rowcount - Ini adalah atribut read-only dan mengembalikan jumlah baris
yang dipengaruhi oleh metode execute ().
• Prosedur berikut menanyakan semua catatan dari tabel EMPLOYEE yang
memiliki gaji lebih dari 1000 10
import pymysql.cursors

# Open database connection


db = pymysql.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method


cursor = db.cursor()

# Prepare SQL query to INSERT a record into the database.


sql = "SELECT * FROM EMPLOYEE \
WHERE INCOME > '%d'" % (1000)
try:
# Execute the SQL command
cursor.execute(sql)

Teknik Informatika - Universitas Ka


# Fetch all the rows in a list of lists.
results = cursor.fetchall() Setelah Anda eksekusi kode diatas, akan muncul hasil
for row in results:
fname = row[0]
seperti dibawah ini :
lname = row[1] fname = Mac, lname = Mohan, age = 20, sex = M,
age = row[2] income = 2000

huripan Kediri
sex = row[3]
income = row[4]
# Now print fetched result
print ("fname = %s,lname = %s,age = %d,sex = %s,income = %d" % \
(fname, lname, age, sex, income ))
except: 11
print ("Error: unable to fetch data")

# menutup koneksi ke server


Update Operation
• Operasi UPDATE pada database apapun berarti mengupdate satu atau lebih catatan,
yang sudah tersedia di database. Prosedur berikut memperbarui semua catatan yang
memiliki SEX sebagai ‘M’. Di sini, kita meningkatkan UMUR semua laki-laki satu tahun.

import pymysql.cursors

# Open database connection


db = pymysql.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method

Teknik Informatika - Universitas Ka


cursor = db.cursor()

# Prepare SQL query to UPDATE required records


sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '%c'" % ('M')
try:

huripan Kediri
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error 12
db.rollback()

# disconnect from server


Delete Operation
• Operasi DELETE diperlukan bila Anda ingin menghapus beberapa catatan dari
database Anda. Berikut ini adalah prosedur untuk menghapus semua catatan dari
EMPLOYEE dimana AGE lebih dari 20
import pymysql.cursors

# Open database connection


db = pymysql.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method


cursor = db.cursor()

Teknik Informatika - Universitas Ka


# Prepare SQL query to DELETE required records
sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20)
try:
# Execute the SQL command

huripan Kediri
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error 13
db.rollback()

# disconnect from server


Penutup
• Selain itu masih ada beberapa operasi sebagai berikut :
• Commit Operation db.commit()
• Rollback Operation db.rollback()
• Disconnect Operation db.close()

Teknik Informatika - Universitas Ka


• Jika Anda menginginkan dokumentasi yang lebih lengkap dari
bahasa pemrograman python, silahkan buka dokumentasi
resmi dari Python - https://docs.python.org/3/

huripan Kediri
14
Terimakasih

Teknik Informatika - Universitas Ka


15

huripan Kediri

Anda mungkin juga menyukai