Python學習之MySQLdb模組

來源:互聯網
上載者:User

標籤:mysql   db   

CentOS下安裝

sudo yum install MySQL-python

可以參考http://www.mikusa.com/python-mysql-docs/index.html  擷取更多資訊

MySQL-python 為Python提供MySQL驅動程式,主要包括兩個組件,_mysql和MySQLdb


  1. 串連資料庫

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.