使用Python對Mysql進行操作,前提是安裝了python-Mysql的安裝包,安裝的方法有多種,可以使用easy_install或者pip 或者是源碼進行安裝。
下面介紹下如何使用Python對Mysql進行操作,下面是一些簡單的例子:
(1).使用Python連接MySQL:
1 import MySQLdb 2 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條.