python操作mysql數據庫(一起學習吧)

編程語言 MySQL Python Delphi 帥帥的日常 2017-06-07

堅持學習,日積月累才能有所增長。本篇是MySQLdb這個庫來對數據庫進行操作。

先上一段代碼,通過操作才能更好的瞭解知識:


import MySQLdb as db

try:

conn=db.connect(host='localhost', #主機名

user='root', #用戶名

passwd='root', #密碼

db='delphi', #使用的數據庫

port=3306, #端口號

charset='utf8' ) #設置字符的編碼格式

cur=conn.cursor()

output = cur.execute('select * from books')

print 'there has %s rows record' % output

results=cur.fetchmany(5)

for r in results:

print r

results=cur.fetchall()

for r in results:

print r[1]

conn.commit()

cur.close()

conn.close()

except db.Error,e:

print "Mysql Error %d: %s" % (e.args[0], e.args[1])


對其中函數的瞭解:

execute(self, query, args):執行單條sql語句,接收的參數為sql語句本身和使用的參數列表,返回值為受影響的行數

fetchall(self):接收全部的返回結果行

fetchmany(self, size=None):接收size條返回結果行.如果size的值大於返回的結果行的數量,則會返回cursor.arraysize條數據

fetchone(self):返回一條結果行

MySQLdb同樣對事務是支持的,標準的方法:

rollback() 回滾

commit() 提交

瞭解數據庫事務的朋友們看名稱的話應該也能看出所代表的意思,這篇文章就先分享此,歡迎各位朋友觀看,留言。大家共同學習,進步~~

相關推薦

推薦中...