標籤:mysql db
CentOS下安裝
sudo yum install MySQL-python
可以參考http://www.mikusa.com/python-mysql-docs/index.html 擷取更多資訊
MySQL-python 為Python提供MySQL驅動程式,主要包括兩個組件,_mysql和MySQLdb
串連資料庫
In [56]: import MySQLdbIn [57]: db=MySQLdb.connect(host=‘127.0.0.1‘,user=‘xxx‘,passwd=‘xxx‘,db=‘xxx‘)
2.建立遊標
為了能夠在多處使用同一個串連,可以建立一個遊標對象
In [60]: cur=db.cursor()
3.執行MySQL查詢操作
建立資料庫表
In [62]: cur.execute("CREATE TABLE song (id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,title TEXT NOT NULL)")
In [67]: songs=(‘Purple Haze‘,‘All Along the Watch Tower‘,‘Foxy Lady‘)In [68]: for song in songs: ....: cur.execute("INSERT INTO song(title) VALUES (%s)",song) ....: print "Auto Increment ID: %s" %cur.lastrowid ....:
In [5]: cur.execute("SELECT * FROM song WHERE id = %s or id = %s",(1,2))
In [7]: numrows=cur.execute("SELECT * FROM song")
4.擷取查詢結果
當執行了任何查詢操作後,可以用fetchall()或者fetchone()擷取
#/usr/bin/pythonimport MySQLdbdb=MySQLdb.connect(host=‘127.0.0.1‘,user=‘xxx‘,passwd=‘xxx‘,db=‘xxx‘)cur=db.cursor()cur.execute("SELECT * FROM account")rows=cur.fetchall()for row in rows: for col in row: print "%s," %col print "\n"
In [70]: cur.execute("SELECT * FROM song WHERE id=1")In [71]: print "ID: %s -- Title: %s" %cur.fetchone()
5.異常處理
import MySQLdbdb=MySQLdb.connect(host=‘127.0.0.1‘,user=‘jialebi‘,passwd=‘jialebi123‘,db=‘dream_android_game_center‘)cur=db.cursor()try: cur.execute("SELECT * FROM account") rows=cur.fetchall()except MySQLdb.Error,e: try: print "MySQL Error [%d] : %s" % (e.args[0],e.args[1]) except IndexError: print "MySQL Error: %s" % str(e)for row in rows: for col in row: print "%s," %col print "\n"
6.清理串連
n [74]: cur.close()In [75]: db.close()
本文出自 “Linux SA John” 部落格,請務必保留此出處http://john88wang.blog.51cto.com/2165294/1530046