Python操作mysql資料庫(封裝基本的增刪改查)
1、安裝MySQL-python-1.2.3.win-amd64-py2.7.exe,這是操作mysql資料庫的python庫,有32位和64位之分,看自機器下載
2、64位機器安裝MySQL-python-1.2.3.win-amd64-py2.7.exe出現 which was not found the regidtry,請點這裡
3、引入mysql庫:
- import MySQLdb
4、獲取資料庫連線:
-
conn=MySQLdb.connect(host='localhost',user='mjy',passwd=
connect連線物件的方法:
close() --關閉的方法
commit() --如果支援事務則提交掛起的事務
rollback() --回滾掛起的事務
cursor() --返回連線的遊標物件
5、獲取遊標:
- #該遊標物件執行查詢操作返回的結果是序列
- cur=con.cursor()
- #該遊標物件執行查詢操作返回的結果是字典(字典可以方便我們隊查詢的結果進行操作,所以我採用這種方法)
-
cur=con.cursor(MySQLdb.cursors.DictCursor)
遊標物件的方法:
callproc(name,[params]) --用來執行儲存過程,接收的引數為儲存過程的名字和引數列表,返回受影響的行數
close() --關閉遊標
execute(sql,[params])--執行sql語句,可以使用引數,(使用引數時,sql語句中用%s進行站位注值),返回受影響的行數
executemany(sql,params)--執行單挑sql語句,但是重複執行引數列表裡的引數,返回受影響的行數
fetchone() --返回結果的下一行
fetchall() --返回結果的 所有行
fetchmany(size)--返回size條記錄,如果size大於返回結果行的數量,則會返回cursor.arraysize條記錄
nextset() --條至下一行
setinputsizes(size)--定義cursor
遊標物件的屬性:
description--結果列的描述,只讀
rowcount --結果中的行數,只讀
arraysize --fetchmany返回的行數,預設為1
6、我自己封裝的一些基本操作
- # -*- coding: cp936 -*-
- import MySQLdb
- class MysqldbHelper:
- #獲取資料庫連線
- def getCon(self):
- try:
- conn=MySQLdb.connect(host='localhost',user='mjy',passwd='123',db='python',port=3306,charset='utf8')
- return conn
- except MySQLdb.Error,e:
- print"Mysqldb Error:%s" % e
- #查詢方法,使用con.cursor(MySQLdb.cursors.DictCursor),返回結果為字典
- def select(self,sql):
- try:
- con=self.getCon()
- print con
- cur=con.cursor(MySQLdb.cursors.DictCursor)
- count=cur.execute(sql)
- fc=cur.fetchall()
- return fc
- except MySQLdb.Error,e:
- print"Mysqldb Error:%s" % e
- finally:
- cur.close()
- con.close()
- #帶引數的更新方法,eg:sql='insert into pythontest values(%s,%s,%s,now()',params=(6,'C#','good book')
- def updateByParam(self,sql,params):
- try:
- con=self.getCon()
- cur=con.cursor()
- count=cur.execute(sql,params)
- con.commit()
- return count
- except MySQLdb.Error,e:
- con.rollback()
- print"Mysqldb Error:%s" % e
- finally:
- cur.close()
- con.close()
- #不帶引數的更新方法
- def update(self,sql):
- try:
- con=self.getCon()
- cur=con.cursor()
- count=cur.execute(sql)
- con.commit()
- return count
- except MySQLdb.Error,e:
- con.rollback()
- print"Mysqldb Error:%s" % e
- finally:
- cur.close()
- con.close()
- if __name__ == "__main__":
- db=MysqldbHelper()
- def get():
- sql="select * from pythontest"
- fc=db.select(sql)
- for row in fc:
- print row["ptime"]
- def ins():
- sql="insert into pythontest values(5,'資料結構','this is a big book',now())"
- count=db.update(sql)
- print count
- def insparam():
- sql="insert into pythontest values(%s,%s,%s,now())"
- params=(6,'C#','good book')
- count=db.updateByParam(sql,params)
- print count
- def delop():
- sql="delete from pythontest where pid=4"
- count=db.update(sql)
- print"the:"+str(count)
- def change():
- sql="update pythontest set pcontent='c# is a good book' where pid=6"
- count=db.update(sql)
- print count
- #get()
- #ins()
- #insparam()
- #delop()
- #change()
附查詢結果: