ภาษา Pythonสามารถทำงานเชื่อมต่อกับฐานข้อมูล ได้เหมือนภาษาอื่นๆ ซึ่งในบทความนี้ จะเป็นการเขียน Python ให้เชื่อมต่อกับฐานข้อมูลเบื้องต้นโดยใช้ฐานข้อมูล PostgreSQL ทำการเพิ่ม แก้ไข หรือ ลบข้อมูลด้วย
ซึ่งจะมีดังนี้
การเขียน Python ให้เชื่อมต่อกับฐานข้อมูล
โค้ด: เลือกทั้งหมด
# -*- coding=utf-8 -*-
import psycopg2 as n
con = None
try:
# connect to database
con = n.connect(host='localhost', user='postgres', password='postgres', port='5432')
cur = con.cursor()
cur.execute('SELECT version()')
var = cur.fetchone()
print var
except n.DatabaseError: # some error
print 'Error %s' %n.DatabaseError
if con:
con.close()
จากโค้ดจะเป็นการเชื่อมต่อฐานข้อมูล PostgreSQL และเขียนดูเวอร์ชั่นของ PostgreSQL
เมื่อรันออกมาแล้วจะเป็นแบบนี้
โค้ด: เลือกทั้งหมด
('PostgreSQL 9.3.9 on x86_64-unknown-linux-gnu, compiled by gcc (Ubuntu 4.8.4-2ubuntu1~14.04) 4.8.4, 64-bit',)
ปล. ไม่สามารถเขียนสร้าง Database จากการเขียน Python ได้ วิธีแก้ไขต้องไปตั้งค่าที่ configuration ของ PostgreSQL ก่อนหรือไม่ก็ไปทำการสร้างในฐานข้อมูลโดยตรงก็ได้ โดยใช้ คำสั่ง SQL
การสร้างตาราง
จะใช้คำสั่ง SQL ในการสร้างตาราง
จะเขียนโดย Python ดังนี้
โค้ด: เลือกทั้งหมด
# -*- coding=utf-8 -*-
import psycopg2 as n
con = None
try:
con = n.connect(host='localhost', database='test', user='postgres', password='postgres', port='5432')
cur = con.cursor()
# Drop test table
cur.execute("DROP TABLE IF EXISTS test_python")
print "Drop test_python table is compeleted"
# Create table as per requirement
sql = """CREATE TABLE IF NOT EXISTS test_python(
id serial NOT NULL,
first_name character varying(100) NOT NULL,
last_name character varying(100) NOT NULL,
favorite_color character varying(100),
CONSTRAINT test_python_pkey PRIMARY KEY (id)
)"""
cur.execute(sql)
con.commit()
print "Create test_python table is compeleted"
except n.DatabaseError: # some error
print 'Error %s' %n.DatabaseError
if con:
con.close()
จากโค้ด เมื่อรันแล้วจะแสดงออกมาเป็นแบบนี้
โค้ด: เลือกทั้งหมด
Drop test_python table is compeleted
Create test_python table is compeleted
ให้ไปดูที่ฐานข้อมูลจะเห็นว่ามีตารางชื่อว่า test_python ถูกสร้างขึ้นมาใหม่
การเพิ่มข้อมูล
จะใช้คำสั่ง SQL ในการเพิ่มข้อมูล
โค้ด: เลือกทั้งหมด
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
จะเขียนโดย Python ดังนี้
โค้ด: เลือกทั้งหมด
# -*- coding=utf-8 -*-
import psycopg2 as n
con = None
try:
con = n.connect(host='localhost', database='test', user='postgres', password='postgres', port='5432')
cur = con.cursor()
sql = """INSERT INTO test_python (first_name, last_name, favorite_color)
VALUES ('Jack', 'Man', 'Yellow')"""
sql = sql.encode('utf-8')
try:
cur.execute(sql)
con.commit()
print 'Insert compelete'
except:
con.pollback()
print 'Insert False'
except n.Error:
print 'Connection error'
if con:
con.close()
จากโค้ด เมื่อรันแล้วจะแสดงออกมาเป็นแบบนี้
ให้ไปดูที่ฐานข้อมูลชื่อว่า test_python จะมีข้อมูลที่เพิ่มเข้าไป
การเขียน Python ให้รับข้อมูลจาก Keyboard
จะใช้คำสั่ง Insert เหมือนเดิมแต่จะทำการวนลูปรับค่าจาก Keyboard
โค้ด: เลือกทั้งหมด
while loop==1:
firstname = raw_input('Input Your First Name : ')
lastname = raw_input('Input Your Last Name : ')
color = raw_input('Input Your Favorite color : ')
if firstname=='esc' or lastname=='esc' or color=='esc':
loop = 0
continue
sql = "INSERT INTO test_python (first_name, last_name, favorite_color) \
VALUES ('%s', '%s', '%s')" % (firstname, lastname, color)
sql = sql.encode('utf-8')
จากโค้ดจะมีการกำหนดว่า ถ้าใส่ esc ไป จะเป็นการจบสิ้นการรับข้อมูล
โค้ด: เลือกทั้งหมด
# -*- coding=utf-8 -*-
import psycopg2 as n
con = None
try:
con = n.connect(host='localhost', database='test', user='postgres', password='postgres', port='5432')
cur = con.cursor()
loop = 1
while loop==1:
firstname = raw_input('Input Your First Name : ')
lastname = raw_input('Input Your Last Name : ')
color = raw_input('Input Your Favorite color : ')
if firstname=='esc' or lastname=='esc' or color=='esc':
loop = 0
continue
sql = "INSERT INTO test_python (first_name, last_name, favorite_color) \
VALUES ('%s', '%s', '%s')" % (firstname, lastname, color)
sql = sql.encode('utf-8')
try:
cur.execute(sql)
con.commit()
print 'Insert compelete'
except:
con.pollback()
print 'Insert False'
except n.Error:
print 'Connection error'
if con:
con.close()
ให้ไปดูที่ฐานข้อมูลชื่อว่า test_python จะมีข้อมูลที่เพิ่มเข้าไป
การเขียน Python ให้แสดงข้อมูล
จะใช้คำสั่ง SELECT มาวนปริ้น
โค้ด: เลือกทั้งหมด
# -*- coding=utf-8 -*-
import psycopg2 as n
con = None
try:
con = n.connect(host='localhost', database='test', user='postgres', password='postgres', port='5432')
cur = con.cursor()
sql = "SELECT * FROM test_python WHERE id <> 0"
sql = sql.encode('utf-8')
cur.execute(sql)
results = cur.fetchall()
for row in results:
id = row[0]
first_name = row[1]
last_name = row[2]
favorite_color = row[3]
print "First Name : %s" %first_name
print "Last Name : %s" %last_name
except n.Error:
print 'Connection error'
if con:
con.close()
เมื่อรันแล้วจะแสดงแบบนี้
โค้ด: เลือกทั้งหมด
First Name : Jack
Last Name : Man
First Name : boy
Last Name : um
First Name : gril
Last Name : um
การแก้ไขข้อมูล
จะใช้คำสั่ง SQL ในการแก้ไขดังนี้
โค้ด: เลือกทั้งหมด
UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;
โค้ด: เลือกทั้งหมด
# -*- coding=utf-8 -*-
import psycopg2 as n
con = None
try:
con = n.connect(host='localhost', database='test', user='postgres', password='postgres', port='5432')
cur = con.cursor()
sql = "UPDATE test_python SET first_name = 'Rose' WHERE id = 1"
try:
cur.execute(sql)
con.commit()
print "Update compelete"
except:
con.rollback()
print "Update False"
except n.Error:
print 'Connection error'
if con:
con.close()
ให้ไปดูที่ฐานข้อมูลชื่อว่า test_python จะมีข้อมูลที่แก้ไข
การลบข้อมูล
จะใช้คำสั่ง SQL ในการลบข้อมูลดังนี้
โค้ด: เลือกทั้งหมด
DELETE FROM table_name
WHERE some_column=some_value;
โค้ด: เลือกทั้งหมด
# -*- coding=utf-8 -*-
import psycopg2 as n
con = None
try:
con = n.connect(host='localhost', database='test', user='postgres', password='postgres', port='5432')
cur = con.cursor()
sql = "DELETE FROM test_python WHERE id > '%d'" %(1)
try:
cur.execute(sql)
con.commit()
print "Delete compelete"
except:
con.rollback()
print "Delete False"
except n.Error:
print 'Connection error'
if con:
con.close()
จากโค้ดรันแล้วจะทำการลบข้อมูลที่ id มากกว่า 1 แล้วให้ไปดูที่ฐานข้อมูลชื่อว่า test_python จะมีข้อมูลที่เหลืออยู่
การลบตาราง
จะใช้คำสั่ง SQL ในการลบตารางดังนี้
โค้ด: เลือกทั้งหมด
# -*- coding=utf-8 -*-
import psycopg2 as n
con = None
try:
con = n.connect(host='localhost', database='test', user='postgres', password='postgres', port='5432')
cur = con.cursor()
sql = "DROP TABLE test_python"
cur.execute(sql)
con.commit()
print "Drop table compelete"
except n.Error:
print 'Connection error'
if con:
con.close()
เมื่อรันแล้ว table ชื่อ test_python จะหายไป
[url=https://www.mindphp.com/%E0%B8%9A%E0%B8%97%E0%B9%80%E0%B8%A3%E0%B8%B5%E0%B8%A2%E0%B8%99%E0%B8%AD%E0%B8%AD%E0%B8%99%E0%B9%84%E0%B8%A5%E0%B8%99%E0%B9%8C/83-python.html]ภาษา Python[/url]สามารถทำงานเชื่อมต่อกับฐานข้อมูล ได้เหมือนภาษาอื่นๆ ซึ่งในบทความนี้ จะเป็นการเขียน Python ให้เชื่อมต่อกับฐานข้อมูลเบื้องต้นโดยใช้ฐานข้อมูล PostgreSQL ทำการเพิ่ม แก้ไข หรือ ลบข้อมูลด้วย
ซึ่งจะมีดังนี้
[b]การเขียน Python ให้เชื่อมต่อกับฐานข้อมูล[/b]
[code=php]# -*- coding=utf-8 -*-
import psycopg2 as n
con = None
try:
# connect to database
con = n.connect(host='localhost', user='postgres', password='postgres', port='5432')
cur = con.cursor()
cur.execute('SELECT version()')
var = cur.fetchone()
print var
except n.DatabaseError: # some error
print 'Error %s' %n.DatabaseError
if con:
con.close() [/code]
จากโค้ดจะเป็นการเชื่อมต่อฐานข้อมูล PostgreSQL และเขียนดูเวอร์ชั่นของ PostgreSQL
เมื่อรันออกมาแล้วจะเป็นแบบนี้
[code]('PostgreSQL 9.3.9 on x86_64-unknown-linux-gnu, compiled by gcc (Ubuntu 4.8.4-2ubuntu1~14.04) 4.8.4, 64-bit',)[/code]
ปล. ไม่สามารถเขียนสร้าง Database จากการเขียน Python ได้ วิธีแก้ไขต้องไปตั้งค่าที่ configuration ของ PostgreSQL ก่อนหรือไม่ก็ไปทำการสร้างในฐานข้อมูลโดยตรงก็ได้ โดยใช้ คำสั่ง SQL
[code]CREATE DATABASE test[/code]
[b]การสร้างตาราง[/b]
จะใช้คำสั่ง SQL ในการสร้างตาราง
[code]CREATE TABLE table_name[/code]
จะเขียนโดย Python ดังนี้
[code=php]# -*- coding=utf-8 -*-
import psycopg2 as n
con = None
try:
con = n.connect(host='localhost', database='test', user='postgres', password='postgres', port='5432')
cur = con.cursor()
# Drop test table
cur.execute("DROP TABLE IF EXISTS test_python")
print "Drop test_python table is compeleted"
# Create table as per requirement
sql = """CREATE TABLE IF NOT EXISTS test_python(
id serial NOT NULL,
first_name character varying(100) NOT NULL,
last_name character varying(100) NOT NULL,
favorite_color character varying(100),
CONSTRAINT test_python_pkey PRIMARY KEY (id)
)"""
cur.execute(sql)
con.commit()
print "Create test_python table is compeleted"
except n.DatabaseError: # some error
print 'Error %s' %n.DatabaseError
if con:
con.close()[/code]
จากโค้ด เมื่อรันแล้วจะแสดงออกมาเป็นแบบนี้
[code]Drop test_python table is compeleted
Create test_python table is compeleted[/code]
ให้ไปดูที่ฐานข้อมูลจะเห็นว่ามีตารางชื่อว่า test_python ถูกสร้างขึ้นมาใหม่
[url=http://w3.mindphp.com/index.php?option=com_my_image&c=download&task=viewpageimage&file=2015-07-29/resize_0f59b45fa3aa7b99b2dcb13d29d1aaae.png][img]http://w3.mindphp.com/index.php?option=com_my_image&c=download&task=viewimage&file=2015-07-29/resize_0f59b45fa3aa7b99b2dcb13d29d1aaae.png[/img][/url]
[b]การเพิ่มข้อมูล[/b]
จะใช้คำสั่ง SQL ในการเพิ่มข้อมูล
[code]INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)[/code]
จะเขียนโดย Python ดังนี้
[code=php]# -*- coding=utf-8 -*-
import psycopg2 as n
con = None
try:
con = n.connect(host='localhost', database='test', user='postgres', password='postgres', port='5432')
cur = con.cursor()
sql = """INSERT INTO test_python (first_name, last_name, favorite_color)
VALUES ('Jack', 'Man', 'Yellow')"""
sql = sql.encode('utf-8')
try:
cur.execute(sql)
con.commit()
print 'Insert compelete'
except:
con.pollback()
print 'Insert False'
except n.Error:
print 'Connection error'
if con:
con.close()[/code]
จากโค้ด เมื่อรันแล้วจะแสดงออกมาเป็นแบบนี้
[code]Insert compelete[/code]
ให้ไปดูที่ฐานข้อมูลชื่อว่า test_python จะมีข้อมูลที่เพิ่มเข้าไป
[url=http://w3.mindphp.com/index.php?option=com_my_image&c=download&task=viewpageimage&file=2015-07-29/resize_d50b54f5582710c1655c4e9255852e9a.png][img]http://w3.mindphp.com/index.php?option=com_my_image&c=download&task=viewimage&file=2015-07-29/resize_d50b54f5582710c1655c4e9255852e9a.png[/img][/url]
[b]การเขียน Python ให้รับข้อมูลจาก Keyboard[/b]
จะใช้คำสั่ง Insert เหมือนเดิมแต่จะทำการวนลูปรับค่าจาก Keyboard
[code=php] while loop==1:
firstname = raw_input('Input Your First Name : ')
lastname = raw_input('Input Your Last Name : ')
color = raw_input('Input Your Favorite color : ')
if firstname=='esc' or lastname=='esc' or color=='esc':
loop = 0
continue
sql = "INSERT INTO test_python (first_name, last_name, favorite_color) \
VALUES ('%s', '%s', '%s')" % (firstname, lastname, color)
sql = sql.encode('utf-8')[/code]
จากโค้ดจะมีการกำหนดว่า ถ้าใส่ esc ไป จะเป็นการจบสิ้นการรับข้อมูล
[code=php]# -*- coding=utf-8 -*-
import psycopg2 as n
con = None
try:
con = n.connect(host='localhost', database='test', user='postgres', password='postgres', port='5432')
cur = con.cursor()
loop = 1
while loop==1:
firstname = raw_input('Input Your First Name : ')
lastname = raw_input('Input Your Last Name : ')
color = raw_input('Input Your Favorite color : ')
if firstname=='esc' or lastname=='esc' or color=='esc':
loop = 0
continue
sql = "INSERT INTO test_python (first_name, last_name, favorite_color) \
VALUES ('%s', '%s', '%s')" % (firstname, lastname, color)
sql = sql.encode('utf-8')
try:
cur.execute(sql)
con.commit()
print 'Insert compelete'
except:
con.pollback()
print 'Insert False'
except n.Error:
print 'Connection error'
if con:
con.close()[/code]
ให้ไปดูที่ฐานข้อมูลชื่อว่า test_python จะมีข้อมูลที่เพิ่มเข้าไป
[url=http://w3.mindphp.com/index.php?option=com_my_image&c=download&task=viewpageimage&file=2015-07-29/resize_1db51c61b61dc76df475c68d66070c18.png][img]http://w3.mindphp.com/index.php?option=com_my_image&c=download&task=viewimage&file=2015-07-29/resize_1db51c61b61dc76df475c68d66070c18.png[/img][/url]
[b]การเขียน Python ให้แสดงข้อมูล[/b]
จะใช้คำสั่ง SELECT มาวนปริ้น
[code=php]# -*- coding=utf-8 -*-
import psycopg2 as n
con = None
try:
con = n.connect(host='localhost', database='test', user='postgres', password='postgres', port='5432')
cur = con.cursor()
sql = "SELECT * FROM test_python WHERE id <> 0"
sql = sql.encode('utf-8')
cur.execute(sql)
results = cur.fetchall()
for row in results:
id = row[0]
first_name = row[1]
last_name = row[2]
favorite_color = row[3]
print "First Name : %s" %first_name
print "Last Name : %s" %last_name
except n.Error:
print 'Connection error'
if con:
con.close()[/code]
เมื่อรันแล้วจะแสดงแบบนี้
[code]First Name : Jack
Last Name : Man
First Name : boy
Last Name : um
First Name : gril
Last Name : um[/code]
[b]การแก้ไขข้อมูล[/b]
จะใช้คำสั่ง SQL ในการแก้ไขดังนี้
[code]UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;[/code]
[code=php]# -*- coding=utf-8 -*-
import psycopg2 as n
con = None
try:
con = n.connect(host='localhost', database='test', user='postgres', password='postgres', port='5432')
cur = con.cursor()
sql = "UPDATE test_python SET first_name = 'Rose' WHERE id = 1"
try:
cur.execute(sql)
con.commit()
print "Update compelete"
except:
con.rollback()
print "Update False"
except n.Error:
print 'Connection error'
if con:
con.close()[/code]
ให้ไปดูที่ฐานข้อมูลชื่อว่า test_python จะมีข้อมูลที่แก้ไข
[url=http://w3.mindphp.com/index.php?option=com_my_image&c=download&task=viewpageimage&file=2015-07-29/resize_0f6e2e9951d687ce5b43bdedf528b59e.png][img]http://w3.mindphp.com/index.php?option=com_my_image&c=download&task=viewimage&file=2015-07-29/resize_0f6e2e9951d687ce5b43bdedf528b59e.png[/img][/url]
[b]การลบข้อมูล[/b]
จะใช้คำสั่ง SQL ในการลบข้อมูลดังนี้
[code]DELETE FROM table_name
WHERE some_column=some_value; [/code]
[code=php]# -*- coding=utf-8 -*-
import psycopg2 as n
con = None
try:
con = n.connect(host='localhost', database='test', user='postgres', password='postgres', port='5432')
cur = con.cursor()
sql = "DELETE FROM test_python WHERE id > '%d'" %(1)
try:
cur.execute(sql)
con.commit()
print "Delete compelete"
except:
con.rollback()
print "Delete False"
except n.Error:
print 'Connection error'
if con:
con.close()[/code]
จากโค้ดรันแล้วจะทำการลบข้อมูลที่ id มากกว่า 1 แล้วให้ไปดูที่ฐานข้อมูลชื่อว่า test_python จะมีข้อมูลที่เหลืออยู่
[url=http://w3.mindphp.com/index.php?option=com_my_image&c=download&task=viewpageimage&file=2015-07-29/resize_a88853da63528a74f3519cf375fc202d.png][img]http://w3.mindphp.com/index.php?option=com_my_image&c=download&task=viewimage&file=2015-07-29/resize_a88853da63528a74f3519cf375fc202d.png[/img][/url]
[b]การลบตาราง[/b]
จะใช้คำสั่ง SQL ในการลบตารางดังนี้
[code]DROP TABLE table_name[/code]
[code=php]# -*- coding=utf-8 -*-
import psycopg2 as n
con = None
try:
con = n.connect(host='localhost', database='test', user='postgres', password='postgres', port='5432')
cur = con.cursor()
sql = "DROP TABLE test_python"
cur.execute(sql)
con.commit()
print "Drop table compelete"
except n.Error:
print 'Connection error'
if con:
con.close()[/code]
เมื่อรันแล้ว table ชื่อ test_python จะหายไป