1捧书、安裝mysql模塊
python2? ubuntu16.4環(huán)境下安裝
先安裝依賴萄凤,否則安裝mysql-python失敗
sudo apt-get install libmysqlclient-dev
安裝mysql-python
pip install mysql-python
python3? ubuntu16.4環(huán)境下安裝
安裝pip3,pip是python2使用的,pip3是python3使用的sudo apt install python3-pip#安裝pymysql模塊pip3 install pymysql
安裝mysql模塊,windows和ubuntu
need-to-insert-img
image.png
image.png
在文件中引入模塊候醒,注意大小寫
importpymysql
2、交互類型
Connection對象:用于建立與數(shù)據(jù)庫的連接
創(chuàng)建對象:調(diào)用connect()方法
conn=connect(參數(shù)列表)#注意參數(shù)的名字參數(shù)host:連接的mysql主機室奏,如果本機是'localhost'參數(shù)port:連接的mysql主機的端口火焰,默認(rèn)是3306參數(shù)db:數(shù)據(jù)庫的名稱參數(shù)user:連接的用戶名參數(shù)password:連接的密碼參數(shù)charset:通信采用的編碼方式劲装,默認(rèn)是'gb2312'胧沫,要求與數(shù)據(jù)庫創(chuàng)建時指定的編碼一致,否則中文會亂碼
對象的方法
close()關(guān)閉連接
commit()事務(wù)占业,所以需要提交才會生效
rollback()事務(wù)绒怨,放棄之前的操作
cursor()返回Cursor對象,用于執(zhí)行sql語句并獲得結(jié)果
Cursor對象的方法:
執(zhí)行sql語句
創(chuàng)建對象:調(diào)用Connection對象的cursor()方法
cursor1=conn.cursor()
close()關(guān)閉
execute(operation [, parameters ])執(zhí)行語句谦疾,返回受影響的行數(shù)
fetchone()執(zhí)行查詢語句時南蹂,獲取查詢結(jié)果集的第一個行數(shù)據(jù),返回一個元組
fetchall()執(zhí)行查詢時念恍,獲取結(jié)果集的所有行六剥,一行構(gòu)成一個元組,再將這些元組裝入一個元組返回
scroll(value[,mode])將行指針移動到某個位置
mode表示移動的方式
mode的默認(rèn)值為relative峰伙,表示基于當(dāng)前行移動到value疗疟,value為正則向下移動,value為負(fù)則向上移動
mode的值為absolute瞳氓,表示基于第一條數(shù)據(jù)的位置策彤,第一條數(shù)據(jù)的位置為0
對象的屬性:
rowcount只讀屬性,表示最近一次execute()執(zhí)行后受影響的行數(shù)
connection獲得當(dāng)前連接對象
3、增刪改
創(chuàng)建testInsert.py文件店诗,向?qū)W生表中插入一條數(shù)據(jù)
importpymysqltry:? ? conn=pymysql.connect(host='localhost',port=3306,db='test1',user='root',passwd='123',charset='utf8')? ? cs1=conn.cursor()? ? count=cs1.execute("insert into students(sname) values('張良')")? ? print(count)? ? conn.commit()? ? cs1.close()? ? conn.close()exceptException,e:? ? print(e)
創(chuàng)建testUpdate.py文件裹刮,修改學(xué)生表的一條數(shù)據(jù)
#encoding=utf-8importpymysqltry:? ? conn=pymysql.connect(host='localhost',port=3306,db='test1',user='root',passwd='123',charset='utf8')? ? cs1=conn.cursor()? ? count=cs1.execute("update students set sname='劉邦' where id=6")? ? print(count)? ? conn.commit()? ? cs1.close()? ? conn.close()exceptException,e:? ? print(e)
創(chuàng)建testDelete.py文件,刪除學(xué)生表的一條數(shù)據(jù)
#encoding=utf-8importpymysqltry:? ? conn=pymysql.connect(host='localhost',port=3306,db='test1',user='root',passwd='123',charset='utf8')? ? cs1=conn.cursor()? ? count=cs1.execute("delete from students where id=6")? ? print(count)? ? conn.commit()? ? cs1.close()? ? conn.close()exceptExceptionase:? ? print(e)
sql語句參數(shù)化:可以防注入
創(chuàng)建testInsertParam.py文件庞瘸,向?qū)W生表中插入一條數(shù)據(jù)
#encoding=utf-8importpymysqltry:? ? conn=pymysql.connect(host='localhost',port=3306,db='test1',user='root',passwd='123',charset='utf8')? ? cs1=conn.cursor()? ? sname=input("請輸入學(xué)生姓名:")? ? params=[sname]? ? count=cs1.execute('insert into students(sname) values(%s)',params)? ? print(count)? ? conn.commit()? ? cs1.close()? ? conn.close()exceptExceptionase:? ? print(e)
其它語句:
cursor對象的execute()方法捧弃,也可以用于執(zhí)行create table等語句
建議在開發(fā)之初,就創(chuàng)建好數(shù)據(jù)庫表結(jié)構(gòu)擦囊,不要在這里執(zhí)行
4塔橡、查詢
創(chuàng)建testSelectOne.py文件,查詢一條學(xué)生信息
importPymysqltry:? ? conn=Pymysql.connect(host='localhost',port=3306,db='test1',user='root',passwd='123',charset='utf8')? ? cur=conn.cursor()? ? cur.execute('select * from students where id=7')? ? result=cur.fetchone()printresult? ? cur.close()? ? conn.close()exceptExceptionase:? ? print(e)
創(chuàng)建testSelectMany.py文件霜第,查詢多條學(xué)生信息
#encoding=utf8importPymysqltry:? ? conn=Pymysql.connect(host='localhost',port=3306,db='test1',user='root',passwd='123',charset='utf8')? ? cur=conn.cursor()? ? cur.execute('select * from students')? ? result=cur.fetchall()printresult? ? cur.close()? ? conn.close()exceptExceptionase:? ? print(e)
5葛家、封裝
觀察前面的文件發(fā)現(xiàn),除了sql語句及參數(shù)不同泌类,其它語句都是一樣的癞谒。
創(chuàng)建MysqlHelper.py文件,定義類:
#encoding=utf8import pymysqlclassMysqlHelper():def__init__(self,host,port,db,user,passwd,charset='utf8'):self.host=hostself.port=portself.db=dbself.user=userself.passwd=passwdself.charset=charsetdefconnect(self):self.conn=MySQLdb.connect(host=self.host,port=self.port,db=self.db,user=self.user,passwd=self.passwd,charset=self.charset)self.cursor=self.conn.cursor()defclose(self):self.cursor.close()self.conn.close()defget_one(self,sql,params=()):? ? ? ? result=Nonetry:self.connect()self.cursor.execute(sql, params)? ? ? ? ? ? result =self.cursor.fetchone()self.close()? ? ? ? except Exception ase:print(e)returnresultdefget_all(self,sql,params=()):? ? ? ? list=()try:self.connect()self.cursor.execute(sql,params)? ? ? ? ? ? list=self.cursor.fetchall()self.close()? ? ? ? except Exception ase:print(e)returnlistdefinsert(self,sql,params=()):returnself.__edit(sql,params)defupdate(self, sql, params=()):returnself.__edit(sql, params)defdelete(self, sql, params=()):returnself.__edit(sql, params)def__edit(self,sql,params):? ? ? ? count=0try:self.connect()? ? ? ? ? ? count=self.cursor.execute(sql,params)self.conn.commit()self.close()? ? ? ? except Exception ase:print(e)returncount
創(chuàng)建testInsertWrap.py文件刃榨,使用封裝好的幫助類完成插入操作
#encoding=utf8fromMysqlHelperimport*sql='insert into students(sname,gender) values(%s,%s)'sname=raw_input("請輸入用戶名:")gender=raw_input("請輸入性別弹砚,1為男,0為女")params=[sname,bool(gender)]mysqlHelper=MysqlHelper('localhost',3306,'test1','root','mysql')count=mysqlHelper.insert(sql,params)ifcount==1:? ? print('ok')else:? ? print('error')
創(chuàng)建testGetOneWrap.py文件枢希,使用封裝好的幫助類完成查詢最新一行數(shù)據(jù)操作
#encoding=utf8fromMysqlHelperimport*sql='select sname,gender from students order by id desc'helper=MysqlHelper('localhost',3306,'test1','root','mysql')one=helper.get_one(sql)print(one)