MySQL與Python的交互

1.交互類型

1.安裝引入模塊

  • 安裝mysql模塊,在windowsubuntu
windows里安裝mysql模塊
Linux里安裝mysql模塊
  • 在文件中引入模塊
    import pymysql

1.Connection對象

  • 用于建立與數(shù)據(jù)庫的連接
  • 創(chuàng)建對象:調(diào)用connect()方法
    conn=connect(參數(shù)列表)
  • 參數(shù)host:連接的mysql主機,如果本機是'localhost'
  • 參數(shù)port:連接的mysql主機的端口,默認是3306
  • 參數(shù)db:數(shù)據(jù)庫的名稱
  • 參數(shù)user:連接的用戶名
  • 參數(shù)password:連接的密碼
  • 參數(shù)charset:通信采用的編碼方式,默認是'gb2312',要求與數(shù)據(jù)庫創(chuàng)建時指定的編碼一致,否則中文會亂碼

2.對象的方法

  • 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ù),返回一個元組
  • next()執(zhí)行查詢語句時,獲取當前行的下一行
  • fetchall()執(zhí)行查詢時,獲取結(jié)果集的所有行,一行構(gòu)成一個元組,再將這些元組裝入一個元組返回
  • scroll(value[,mode])將行指針移動到某個位置
  • mode表示移動的方式
  • mode的默認值為relative,表示基于當前行移動到value,value為正則向下移動,value為負則向上移動。相對的
  • mode的值為absolute,表示基于第一條數(shù)據(jù)的位置,第一條數(shù)據(jù)的位置為0,絕對的。

舉個例子便于理解

# 導(dǎo)入python操作mysql的模塊
import pymysql

# 獲取連接對象
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)

#向上移動一行
cur.scroll(-1)

#向下移動一行
cur.scroll(1)

cur.scroll(1,mode='absolute')   絕對的,這里指的是第一行
cur.scroll(1,mode='relative')   相對的

#獲取所有行的數(shù)據(jù)
dataAll = cur.fetchall()
print(dataAll)

for temp in dataAll:
     print(temp)
     print(dataAll[-1][2])      #dataAll[-1]得到的是一個用戶所有的信息,dataAll[-1][2]獲取最后一個人的密碼


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()

3.對象的屬性

  • rowcount只讀屬性,表示最近一次execute()執(zhí)行后受影響的行數(shù)
  • connection獲得當前連接對象

2.增刪改查(CRUD)

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文件,修改學生表的一條數(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文件,刪除學生表的一條數(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文件,查詢一條學生信息
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生信息
#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ù)

# 導(dǎo)入python操作mysql的模塊
import pymysql
import time

# 獲取連接對象
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日')      #這里我們就用到了時間與字符串的相互轉(zhuǎn)換(詳情見MySQL高級)

params = [name,pwd,birthday]
# 執(zhí)行,返回值。如果是增刪改,返回受影響的行數(shù),如果是查詢,返回查詢的行數(shù)
count = cur.execute(sql,params)
#提交
conn.commit()
print('受影響的行數(shù):%s'%count)
# 關(guān)閉
cur.close()
conn.close()

實例二:拋出異常

# 導(dǎo)入python操作mysql的模塊
import pymysql

try:
    conn = None
    cur = None
    # 獲取連接對象
    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:
    # 打印異常信息,測試時候使用,項目上線,去掉
    print(str(ex))
    # 將異常繼續(xù)拋出
    # raise
finally:
    if cur != None:
        cur.close()
    if conn != None:
        conn.close()

實例三:

# 導(dǎo)入python操作mysql的模塊
import pymysql

# 獲取連接對象
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()

3.封裝

這個庫的名字:mySqlHelper

    python操作mysql進行增刪改查的封裝

    1、增刪改,代碼類似
    2、查詢

    代碼分析
    1、獲取連接對象
    2、sql語句不同,參數(shù)不同
    3、獲取執(zhí)行對象
        增刪改
        查詢
            1、fetchone
            2、fetchall
    4、處理結(jié)果
    5、關(guān)閉

    面向?qū)ο? 建立類,封裝屬性和函數(shù) '''

import pymysql
class MysqlHelper:
    '''python操作mysql的增刪改查的封裝'''

    def __init__(self, host, user, password, database, port=3306, charset='utf8'):
        '''
        初始化參數(shù)
        :param host:        主機
        :param user:        用戶名
        :param password:    密碼
        :param database:    數(shù)據(jù)庫
        :param port:        端口號,默認是3306
        :param charset:     編碼,默認是utf8
        '''
        self.host = host
        self.port = port
        self.database = database
        self.user = user
        self.password = password
        self.charset = charset

    def connect(self):
        '''
        獲取連接對象和執(zhí)行對象
        :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語句對象的參數(shù)元組,默認值為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語句對象的參數(shù)列表,默認值為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語句對象的參數(shù)列表,默認值為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語句對象的參數(shù)列表,默認值為None
        :return:        受影響的行數(shù)
        '''
        return self.__item(sql, params)

    def insert(self, sql, params=None):
        '''
        執(zhí)行新增
        :param sql:     sql語句
        :param params:  sql語句對象的參數(shù)列表,默認值為None
        :return:        受影響的行數(shù)
        '''
        return self.__item(sql, params)

    def delete(self, sql, params=None):
        '''
        執(zhí)行刪除
        :param sql:     sql語句
        :param params:  sql語句對象的參數(shù)列表,默認值為None
        :return:        受影響的行數(shù)
        '''
        return self.__item(sql, params)

    def close(self):
        '''
        關(guān)閉執(zhí)行工具和連接對象
        '''
        if self.cur != None:
            self.cur.close()
        if self.conn != None:
            self.conn.close()

1.測試查詢多條數(shù)據(jù)

import mysqlHelper

# 初始化對象
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.測試查詢一條數(shù)據(jù)

import mysqlHelper

# 初始化對象
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.測試增刪改

import mysqlHelper
import time

# 初始化對象
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('輸入編號:')
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.登錄和注冊

登錄和注冊的時候需要對密碼進行加密

注意:

  • 需要對密碼進行加密
  • 如果使用md5加密,則密碼包含32個字符
  • 如果使用sha1加密,則密碼包含40個字符,這里使用這種方式
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);

登錄與注冊

from mysqlHelper import MysqlHelper
import hashlib


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():
    '''注冊'''
    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()

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容