使用Python來對MySQL資料庫進行操作

來源:互聯網
上載者:User

標籤:

使用Python對Mysql進行操作,前提是安裝了python-Mysql的安裝包,安裝的方法有多種,可以使用easy_install或者pip  或者是源碼進行安裝。

下面介紹下如何使用Python對Mysql進行操作,下面是一些簡單的例子:

(1).使用Python串連MySQL:

1 import MySQLdb2 3 try:4     conn = MySQLdb.connect(host="localhost",,user=‘root‘,passwd="sina.com",db="mysql",port=3307)5 except MySQLdb.OperationalError,e:6     print "the error msg is :",e

(2).使用Python查詢MySQL資料:

 1 import MySQLdb 2   3 try: 4     conn=MySQLdb.connect(host=‘localhost‘,user=‘root‘,passwd=‘root‘,db=‘test‘,port=3306) 5     cur=conn.cursor() 6     cur.execute(‘select * from user‘) 7     cur.close() 8     conn.close() 9 except MySQLdb.Error,e:10      print "Mysql Error %d: %s" % (e.args[0], e.args[1])

(3).使用Python添加和更新MySQL資料:

 1 import MySQLdb 2   3 try: 4     conn=MySQLdb.connect(host=‘localhost‘,user=‘root‘,passwd=‘root‘,port=3306) 5     cur=conn.cursor() 6       7     cur.execute(‘create database if not exists python‘) 8     conn.select_db(‘python‘) 9     cur.execute(‘create table test(id int,info varchar(20))‘)10      11     value=[1,‘hi rollen‘]12     cur.execute(‘insert into test values(%s,%s)‘,value)13      14     values=[]15     for i in range(20):16         values.append((i,‘hi rollen‘+str(i)))17          18     cur.executemany(‘insert into test values(%s,%s)‘,values)19  20     cur.execute(‘update test set info="I am rollen" where id=3‘)21  22     conn.commit()23     cur.close()24     conn.close()25  26 except MySQLdb.Error,e:27      print "Mysql Error %d: %s" % (e.args[0], e.args[1])
import MySQLdb try:    conn=MySQLdb.connect(host=‘localhost‘,user=‘root‘,passwd=‘root‘,port=3306)    cur=conn.cursor()         conn.select_db(‘python‘)     count=cur.execute(‘select * from test‘)    print ‘there has %s rows record‘ % count     result=cur.fetchone()    print result    print ‘ID: %s info %s‘ % result     results=cur.fetchmany(5)    for r in results:        print r     print ‘==‘*10    cur.scroll(0,mode=‘absolute‘)     results=cur.fetchall()    for r in results:        print r[1]          conn.commit()    cur.close()    conn.close() except MySQLdb.Error,e:     print "Mysql Error %d: %s" % (e.args[0], e.args[1])

(4).經常使用的一些API方法:

 1 commit() 提交 2 rollback() 復原 3  4 cursor用來執行命令的方法: 5 callproc(self, procname, args):用來執行預存程序,接收的參數為預存程序名和參數列表,傳回值為受影響的行數 6 execute(self, query, args):執行單條sql語句,接收的參數為sql語句本身和使用的參數列表,傳回值為受影響的行數 7 executemany(self, query, args):執行單挑sql語句,但是重複執行參數列表裡的參數,傳回值為受影響的行數 8 nextset(self):移動到下一個結果集 9 10 cursor用來接收傳回值的方法:11 fetchall(self):接收全部的返回結果行.12 fetchmany(self, size=None):接收size條返回結果行.如果size的值大於返回的結果行的數量,則會返回cursor.arraysize條資料.13 fetchone(self):返回一條結果行.14 scroll(self, value, mode=‘relative‘):移動指標到某一行.如果mode=‘relative‘,則表示從當前所在行移動value條,如果 mode=‘absolute‘,則表示從結果集的第一行移動value條.

 

使用Python來對MySQL資料庫進行操作

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.