最近在練習 Python,希望從一些範例中練習並改進成自己的程式,主要希望可以在系統方面補足一些 bash 做不到或不夠好的地方
在此部落格沒有侷限範圍,但此篇使用的是 Python 2.7,因為 MySQL-Python 目前尚未支援 Python 3 以上的版本 (官方有提到即將推出)
在此練習的環境是使用 Mac OSX 10.11,也適用於 CentOS 等 Linux 作業系統。
MySQL-Python 官方文件
- connect 建立連線
- cursor() 使用 connect 建立連線並返回游標
- commit() 提交
- rollback() 因為交易異常,回滾取消交易。
- close() 關閉連線
Python 安裝 MySQL-Python 模組
到 MySQL-Python 官方下載最新版本,或是 GitHub
$ tar zxvf MySQL-python-1.2.5.tar.gz $ cd MySQL-python-1.2.5 $ python setup.py build $ python setup.py install
MySQL-Python 的使用範例
撈取 MySQL tables 並且 show 出資料
#!/usr/bin/python
#coding=UTF-8
HOST="192.168.121.21"
USER="root"
PASS="rootpass"
DBNAME="dbdata"
PORT="3306"
import MySQLdb
try:
db = MySQLdb.connect(HOST, USER, PASS, DBNAME, charset='utf8')
# 執行SQL statement
cursor = db.cursor()
cursor.execute("SELECT * FROM data")
# 撈取多筆資料
results = cursor.fetchall()
# 迴圈撈取資料
for record in results:
col0 = record[0]
col1 = record[1]
col2 = record[2]
col3 = record[3]
print "%s, %s, %s, %s" % (col0, col1, col2, col3)
# 關閉連線
db.close()
except MySQLdb.Error as e:
print "Error %d: %s" % (e.args[0], e.args[1])
印出 MySQL 版本資訊
#!/usr/bin/python
#coding=UTF-8
HOST="192.168.121.21"
USER="root"
PASS="rootpass"
DBNAME="dbdata"
PORT="3306"
import MySQLdb
try:
db = MySQLdb.connect(HOST, USER, PASS, DBNAME, charset='utf8')
# 執行SQL statement
cursor = db.cursor()
cursor.execute("SELECT VERSION()")
# 撈取多筆資料
results = cursor.fetchall()
# 迴圈撈取資料
for record in results:
col0 = record[0]
print "%s" % col0
# 關閉連線
db.close()
except MySQLdb.Error as e:
print "Error %d: %s" % (e.args[0], e.args[1])
