1.安裝引入模塊
- 安裝MySQL模塊,在windows和ubuntu中
windows里安裝mysql模塊
linux里安裝mysql模塊
- 在文件中引入模塊import pymysql
2.Connection對(duì)象
- 用于建立與數(shù)據(jù)庫的連接
- 創(chuàng)建對(duì)象:調(diào)用connect()方法
- conn=connect(參數(shù)列表)
- 參數(shù)host:連接的mysql主機(jī),如果本機(jī)是'localhost'
- 參數(shù)port:連接的mysql主機(jī)的端口,默認(rèn)是3306
- 參數(shù)db:數(shù)據(jù)庫的名稱
- 參數(shù)user:連接的用戶名
- 參數(shù)password:連接的密碼
- 參數(shù)charset:通信采用的編碼方式,默認(rèn)是'gb2312',要求與數(shù)據(jù)庫創(chuàng)建時(shí)指定的編碼一致,否則中文會(huì)亂碼
3.對(duì)象的方法
- close()關(guān)閉連接
- commit()事務(wù),所以需要提交才會(huì)生效
- rollback()事務(wù),放棄之前的操作
- cursor()返回Cursor對(duì)象,用于執(zhí)行sql語句并獲得結(jié)果
Cursor對(duì)象
- 執(zhí)行sql語句
- 創(chuàng)建對(duì)象:調(diào)用Connection對(duì)象的cursor()方法
- cursor1=conn.cursor()
對(duì)象的方法
- close()關(guān)閉
- execute(operation [, parameters ])執(zhí)行語句,返回受影響的行數(shù)
- fetchone()執(zhí)行查詢語句時(shí),獲取查詢結(jié)果集的第一個(gè)行數(shù)據(jù),返回一個(gè)元組
- next()執(zhí)行查詢語句時(shí),獲取當(dāng)前行的下一行
- fetchall()執(zhí)行查詢時(shí),獲取結(jié)果集的所有行,一行構(gòu)成一個(gè)元組,再將這些元組裝入一個(gè)元組返回
- scroll(value[,mode])將行指針移動(dòng)到某個(gè)位置
- mode表示移動(dòng)的方式
- mode的默認(rèn)值為relative,表示基于當(dāng)前行移動(dòng)到value,value為正則向下移動(dòng),value為負(fù)則向上移動(dòng)。相對(duì)的
- mode的值為absolute,表示基于第一條數(shù)據(jù)的位置,第一條數(shù)據(jù)的位置為0,絕對(duì)的。
舉例便于理解
# 導(dǎo)入Python操作mysql的模塊 import pymysql # 獲取連接對(duì)象 conn = pymysql.connect(host='127.0.0.1', user='root', password='123456', database='python01', port=3306, charset='utf8') # 獲取執(zhí)行工具 cur = conn.cursor() # sql語句,增刪改 #sql = 'select birthday from t_user' sql = 'select id,name,pwd,birthday from t_user' # 執(zhí)行,返回值。如果是增刪改,返回受影響的行數(shù),如果是查詢,返回查詢的行數(shù) count = cur.execute(sql) print('查詢的結(jié)果有%s條數(shù)據(jù)'%count) # 獲取第一行 dateOne = cur.fetchone() print(dateOne) # 向上移動(dòng)一行 cur.scroll(-1) # 向下移動(dòng)一行 cur.scroll(1) cur.scroll(1,mode='absolute') 絕對(duì)的,這里指的是第一行 cur.scroll(1,mode='relative') 相對(duì)的 #獲取所有行的數(shù)據(jù) dataAll = cur.fetchall() print(dataAll) for temp in dataAll: print(temp) print(dataAll[-1][2]) #dataAll[-1]得到的是一個(gè)用戶所有的信息,dataAll[-1][2]獲取最后一個(gè)人的密碼 for temp in cur: print(temp) s = 'id:%s,name:%s,pwd:%s,birthday:%s' for temp in dataAll: print(s%(temp[0],temp[1],temp[2],temp[3])) # 關(guān)閉 cur.close() conn.close()
4.對(duì)象的屬性
- rowcount只讀屬性,表示最近一次execute()執(zhí)行后受影響的行數(shù)
- connection獲得當(dāng)前連接對(duì)象
增刪改查
1.增
- 創(chuàng)建testInsert.py文件,向?qū)W生表中插入一條數(shù)據(jù)
#encoding=utf-8 import pymysql try: conn=pymysql.connect(host='localhost',port=3306,db='test1',user='root',passwd='mysql',charset='utf8') cs1=conn.cursor() count=cs1.execute("insert into students(sname) values('張良')") print(count) conn.commit() cs1.close() conn.close() except Exception,e: print(e)
2.修改
- 創(chuàng)建testUpdate.py文件,修改學(xué)生表的一條數(shù)據(jù)
#encoding=utf-8 import pymysql try: conn=pymysql.connect(host='localhost',port=3306,db='test1',user='root',passwd='mysql',charset='utf8') cs1=conn.cursor() count=cs1.execute("update students set sname='劉邦' where id=6") print(count) conn.commit() cs1.close() conn.close() except Exception,e: print(e)
3.刪除
- 創(chuàng)建testDelete.py文件,刪除學(xué)生表的一條數(shù)據(jù)
#encoding=utf-8 import pymysql try: conn=pymysql.connect(host='localhost',port=3306,db='test1',user='root',passwd='mysql',charset='utf8') cs1=conn.cursor() count=cs1.execute("delete from students where id=6") print(count) conn.commit() cs1.close() conn.close() except Exception as e: print(e)
4.查
- 創(chuàng)建testSelectOne.py文件,查詢一條學(xué)生信息
import Pymysql try: conn=Pymysql.connect(host='localhost',port=3306,db='test1',user='root',passwd='mysql',charset='utf8') cur=conn.cursor() cur.execute('select * from students where id=7') result=cur.fetchone() print result cur.close() conn.close() except Exception as e: print(e)
- 創(chuàng)建testSelectMany.py文件,查詢?nèi)繉W(xué)生信息
#encoding=utf8 import Pymysql try: conn=Pymysql.connect(host='localhost',port=3306,db='test1',user='root',passwd='mysql',charset='utf8') cur=conn.cursor() cur.execute('select * from students') result=cur.fetchall() print result cur.close() conn.close() except Exception as e: print(e)
實(shí)例一:參數(shù)
# 導(dǎo)入python操作mysql的模塊 import pymysql import time # 獲取連接對(duì)象 conn = pymysql.connect(host='127.0.0.1', user='root', password='123456', database='python01', port=3306, charset='utf8') # 獲取執(zhí)行工具 cur = conn.cursor() # sql語句,增刪改,sql注入 sql = 'insert into t_user(name,pwd,birthday) values(%s,%s,%s)' # 參數(shù)列表 name = input('輸入姓名:') pwd = input('輸入密碼:') birthday = input('輸入生日:') # 2017年10月01日-->日期struct_time(--->2017-10-01) birthday = time.strptime(birthday,'%Y年%m月%d日') #這里我們就用到了時(shí)間與字符串的相互轉(zhuǎn)換(詳情見MySQL高級(jí)) params = [name,pwd,birthday] # 執(zhí)行,返回值。如果是增刪改,返回受影響的行數(shù),如果是查詢,返回查詢的行數(shù) count = cur.execute(sql,params) #提交 conn.commit() print('受影響的行數(shù):%s'%count) # 關(guān)閉 cur.close() conn.close()
實(shí)例二:拋出異常
# 導(dǎo)入python操作mysql的模塊 import pymysql try: conn = None cur = None # 獲取連接對(duì)象 conn = pymysql.connect(host='127.0.0.1', user='root', password='123456', database='python01', port=3306, charset='utf8') # 模擬異常 # a = 1 / 0 # 獲取執(zhí)行工具 cur = conn.cursor() # sql語句,增刪改 sql = 'insert into t_user(name,pwd,birthday) values("小伊","123456",str_to_date("2017年10月20日","%Y年%m月%d日"))' # 執(zhí)行,返回值。如果是增刪改,返回受影響的行數(shù),如果是查詢,返回查詢的行數(shù) count = cur.execute(sql) # 提交 conn.commit() print('受影響的行數(shù):%s' % count) except Exception as ex: # 打印異常信息,測(cè)試時(shí)候使用,項(xiàng)目上線,去掉 print(str(ex)) # 將異常繼續(xù)拋出 # raise finally: if cur != None: cur.close() if conn != None: conn.close()
實(shí)例三:
# 導(dǎo)入python操作mysql的模塊 import pymysql # 獲取連接對(duì)象 conn = pymysql.connect(host='127.0.0.1', user='root', password='123456', database='python01', port=3306, charset='utf8') # 獲取執(zhí)行工具 cur = conn.cursor() # sql語句,增刪改 #sql = 'select birthday from t_user' sql = 'select id,name,pwd,birthday from t_user' # 執(zhí)行,返回值。如果是增刪改,返回受影響的行數(shù),如果是查詢,返回查詢的行數(shù) count = cur.execute(sql) print('查詢的結(jié)果有%s條數(shù)據(jù)'%count) # 獲取第一行 # dateOne = cur.fetchone() # print(dateOne) # for temp in cur: # print(temp) s = 'id:%s,name:%s,pwd:%s,birthday:%s' for temp in dataAll: print(s%(temp[0],temp[1],temp[2],temp[3])) # 關(guān)閉 cur.close() conn.close()
封裝
我們可以封裝一個(gè)py文件,方便每次進(jìn)行調(diào)用。把這個(gè)庫定義為:mySqlHelper
""" python操作mysql進(jìn)行增刪改查的封裝 1、增刪改,代碼類似 2、查詢 代碼分析 1、獲取連接對(duì)象 2、sql語句不同,參數(shù)不同 3、獲取執(zhí)行對(duì)象 """ import pymysql class MysqlHelper: '''python操作mysql的增刪改查的封裝''' def __init__(self, host, user, password, database, port=3306, charset='utf8'): ''' 初始化參數(shù) :param host: 主機(jī) :param user: 用戶名 :param password: 密碼 :param database: 數(shù)據(jù)庫 :param port: 端口號(hào),默認(rèn)是3306 :param charset: 編碼,默認(rèn)是utf8 ''' self.host = host self.port = port self.database = database self.user = user self.password = password self.charset = charset def connect(self): ''' 獲取連接對(duì)象和執(zhí)行對(duì)象 :return: ''' self.conn = pymysql.connect(host=self.host, user=self.user, password=self.password, database=self.database, port=self.port, charset=self.charset) self.cur = self.conn.cursor() def fetchone(self, sql, params=None): ''' 根據(jù)sql和參數(shù)獲取一行數(shù)據(jù) :param sql: sql語句 :param params: sql語句對(duì)象的參數(shù)元組,默認(rèn)值為None :return: 查詢的一行數(shù)據(jù) ''' dataOne = None try: count = self.cur.execute(sql, params) if count != 0: dataOne = self.cur.fetchone() except Exception as ex: print(ex) finally: self.close() return dataOne def fetchall(self, sql, params=None): ''' 根據(jù)sql和參數(shù)獲取一行數(shù)據(jù) :param sql: sql語句 :param params: sql語句對(duì)象的參數(shù)列表,默認(rèn)值為None :return: 查詢的一行數(shù)據(jù) ''' dataall = None try: count = self.cur.execute(sql, params) if count != 0: dataall = self.cur.fetchall() except Exception as ex: print(ex) finally: self.close() return dataall def __item(self, sql, params=None): ''' 執(zhí)行增刪改 :param sql: sql語句 :param params: sql語句對(duì)象的參數(shù)列表,默認(rèn)值為None :return: 受影響的行數(shù) ''' count = 0 try: count = self.cur.execute(sql, params) self.conn.commit() except Exception as ex: print(ex) finally: self.close() return count def update(self, sql, params=None): ''' 執(zhí)行修改 :param sql: sql語句 :param params: sql語句對(duì)象的參數(shù)列表,默認(rèn)值為None :return: 受影響的行數(shù) ''' return self.__item(sql, params) def insert(self, sql, params=None): ''' 執(zhí)行新增 :param sql: sql語句 :param params: sql語句對(duì)象的參數(shù)列表,默認(rèn)值為None :return: 受影響的行數(shù) ''' return self.__item(sql, params) def delete(self, sql, params=None): ''' 執(zhí)行刪除 :param sql: sql語句 :param params: sql語句對(duì)象的參數(shù)列表,默認(rèn)值為None :return: 受影響的行數(shù) ''' return self.__item(sql, params) def close(self): ''' 關(guān)閉執(zhí)行工具和連接對(duì)象 ''' if self.cur != None: self.cur.close() if self.conn != None: self.conn.close()
測(cè)試
1.測(cè)試查詢多條數(shù)據(jù)
import mysqlHelper # 初始化對(duì)象 helper = mysqlHelper.MysqlHelper('127.0.0.1', 'root', '123456', 'python01') # 連接 helper.connect() # sql sql = 'select * from t_user where name = %s and id > %s' # params params = ['小茗',1] # 執(zhí)行 data = helper.fetchall(sql, params) # 判斷 if data: for temp in data: print(temp) else: # None,False,0 print('沒有數(shù)據(jù).') helper.close()
2.測(cè)試查詢一條數(shù)據(jù)
import mysqlHelper # 初始化對(duì)象 helper = mysqlHelper.MysqlHelper('127.0.0.1', 'root', '123456', 'python01') # 連接 helper.connect() # sql sql = 'select * from t_user where id = %s' #sql = 'select * from t_user where id = 1' # params params = [2] # 執(zhí)行 data = helper.fetchone(sql, params) #data = helper.fetchone(sql) # 判斷 if data: print(data) else: # None,False,0 print('沒有數(shù)據(jù).')
3.測(cè)試增刪改
import mysqlHelper import time # 初始化對(duì)象 helper = mysqlHelper.MysqlHelper('127.0.0.1', 'root', '123456', 'python01') # 連接 helper.connect() # sql sql = 'update t_user set name =%s,pwd=%s,birthday=%s where id=%s' # params id = input('輸入編號(hào):') name = input('輸入姓名:') pwd = input('輸入密碼:') birthday = time.strptime(input('輸入生日:'), '%Y年%m月%d日') params = [name, pwd, birthday,id] # 執(zhí)行 count = helper.update(sql, params) # 判斷 if count: print('操作成功.') else: # None,False,0 print('操作失敗.')
4.簡(jiǎn)單的登錄和注冊(cè)
做項(xiàng)目的時(shí)候會(huì)有個(gè)嘗試登錄和注冊(cè)的時(shí)候需要對(duì)密碼進(jìn)行加密進(jìn)行存儲(chǔ),剛好結(jié)合sql語句進(jìn)行一個(gè)簡(jiǎn)單的交互。
注意:
- 需要對(duì)密碼進(jìn)行加密
- 如果使用md5加密,則密碼包含32個(gè)字符
- 如果使用sha1加密,則密碼包含40個(gè)字符,這里使用這種方式
create table userinfos( id int primary key auto_increment, uname varchar(20), upwd char(40), isdelete bit default 0 ); /* ret = doPwd('123') print(ret) 結(jié)果:40bd001563085fc35165329ea1ff5c5ecbdbbeef */ -- 插入如下數(shù)據(jù),用戶名為123,密碼為123,這是sha1加密后的值 insert into userinfos values(1,'123','40bd001563085fc35165329ea1ff5c5ecbdbbeef',0);
登錄與注冊(cè)
import hashlib from mysqlHelper import MysqlHelper def login(): '''登錄''' name = input('輸入用戶名:') pwd = input('輸入密碼:') #加密 pwd = doPwd(pwd) helper = MysqlHelper('127.0.0.1', 'root', '123456', 'python01') helper.connect() sql = 'select * from t_user where name=%s and pwd=%s' params = [name, pwd] data = helper.fetchone(sql, params) if data: print('登錄成功.') else: # None,False,0 print('登錄失敗.') def doPwd(pwd): '''sha1編碼''' mysha1 = hashlib.sha1() mysha1.update(pwd.encode('utf-8')) pwd = mysha1.hexdigest() return pwd def register(): '''注冊(cè)''' name = input('輸入用戶名:') pwd = input('輸入密碼:') # 加密 pwd = doPwd(pwd) helper = MysqlHelper('127.0.0.1', 'root', '123456', 'python01') helper.connect() sql = 'insert into t_user(name,pwd) values(%s,%s)' params = [name, pwd] count = helper.insert(sql, params) if count: print('操作成功.') else: # None,False,0 print('操作失敗.') if __name__ == '__main__': #register() login()
實(shí)際項(xiàng)目中的登錄注冊(cè)往往加入了各種驗(yàn)證,這里的代碼只是一個(gè)簡(jiǎn)單的登錄注冊(cè),只為了學(xué)習(xí)交流。
來源網(wǎng)絡(luò),侵權(quán)聯(lián)系刪除