Python小推车python学习

Python学习打call第四十七天:mysqlclient操作

2019-03-25  本文已影响12人  暖A暖

1.mysqlclient基本使用

create database XKD_Python_Course;
use XKD_Python_Course;
CREATE TABLE `students` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `age` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
grant [权限的名称 select insert ... | all] on 数据库.表名 to 用户名@主机地址 with grant option;
flush privileges;

2.什么是cursor

3.游标支持的方法有

4.插入操作

import MySQLdb
connect = None
cursor = None
try:
    connect = MySQLdb.connect(host='localhost',
                                  user='Mark',
                                  password='Mark123456',
                                  database='Student',
                                  use_unicode=True,
                                  charset='utf8')
    cursor = connect.cursor()
except Exception as e:
    print(e)
    connect.close()
try:
    if cursor:
        result = cursor.execute("insert into students (name, age) values ('robby', 27)")
        print('result = {}'.format(result))
        connect.commit()
except Exception as e:
    print(e)
    connect.rollback()
finally:
    if cursor:
        cursor.close()
    if connect:
        connect.close()

5.查询数据

import MySQLdb
from pprint import pprint
connect = None
cursor = None
try:
    connect = MySQLdb.connect(host='localhost',
                                  user='robby',
                                  password='Mark123456',
                                  database='Student',
                                  use_unicode=True,
                                  charset='utf8')
    cursor = connect.cursor()
except Exception as e:
    print(e)
    connect.close()
try:
    if cursor:
        cursor.execute('select * from students')
        one_result = cursor.fetchone()
        many_result = cursor.fetchmany(9)
        all_result = cursor.fetchall()
        pprint(one_result)
        pprint(many_result)
        pprint(all_result)
except Exception as e:
    print(e)
    connect.rollback()
finally:
    if cursor:
        cursor.close()
    if connect:
        connect.close()

6.使用上下文管理

import MySQLdb
connect = MySQLdb.connect(host='localhost',
                          user='robby',
                          password='Mark123456',
                          database='Student',
                          use_unicode=True,
                          charset='utf8')
with connect as cursor:
    # 如果这里对cursor做上下文管理,当退出cursor的上下文管理,会自动关闭cursor对象
    cursor.execute("insert into students (name, age) values ('robby', 27)")
# 此时连接还没有关闭
cursor.execute("insert into students (name, age) values ('robby', 28)")
connect.close()

7.Queue模块

##############queue模块中的Queue
from threading import Thread, Event
from queue import Queue
import time
def write(q: Queue, e: Event):
    for value in range(100):
        print('put {} to queue'.format(value))
        q.put(value)
        time.sleep(0.5)
    else:
        e.set()
def read(q: Queue, e: Event):
    while True :
        if not q.empty() or not e.is_set():
            value = q.get()
            print('get {} from queue'.format(value))
            time.sleep(1)
        else:
            break
if __name__ == '__main__':
    q = Queue()
    e = Event()
    tw = Thread(target=write, args=(q,e))
    tr = Thread(target=read, args=(q,e))
    tw.start()
    tr.start()
    tw.join()
    tr.join()
    print('finished ')


############multiprocessing模块的queue
from multiprocessing import Process,Queue, Event
import time
def write(q: Queue, e: Event):
    for value in range(100):
        print('put {} to queue'.format(value))
        q.put(value)
        time.sleep(0.5)
    else:
        e.set()
def read(q: Queue, e: Event):
    while True :
        if not q.empty() or not e.is_set():
            value = q.get()
            print('get {} from queue'.format(value))
            time.sleep(1)
        else:
            break
if __name__ == '__main__':
    q = Queue()
    e = Event()
    pw = Process(target=write, args=(q,e))
    pr = Process(target=read, args=(q,e))
    pw.start()
    pr.start()
    pw.join()
    pr.join()
    print('finished ')

Queue模块实现了多生产者多消费者队列,尤其适合多线程编程,Queue类中实现了所有需要的锁原语,Queue模块实现了三种类型队列:

8.Queue队列对象的方法

9.使用Queue构建连接池

from queue import Queue
import MySQLdb
class ConnectPool:
    def __init__(self, size=5, *args, **kwargs):
        if not isinstance(size, int) or size < 1:
            size = 10
        self.__pool = Queue(size)
        for i in range(size):
            self.__pool.put(MySQLdb.connect(*args, **kwargs))
    @property
    def connect(self):
        return self.__pool.get()
    @connect.setter
    def connect(self, conn):
        self.__pool.put(conn)
if __name__ == '__main__':
    # 构建连接池
    pool = ConnectPool(host='localhost',
                       user='robby',
                       password='robby123456',
                       database='XKD_Python_Course',
                       use_unicode=True,
                       charset='utf8')
    # 获取一个连接
    connect = pool.connect
    #
    with connect as cursor:
        with cursor:
            sql = 'select * from students'
            cursor.execute(sql)
            print(cursor.fetchall())

10.线程连接池实现

from queue import Queue
import MySQLdb
import threading
class ConnectPool:
    def __init__(self, size=5, *args, **kwargs):
        if not isinstance(size, int) or size < 1:
            size = 10
        self.__pool = Queue(size)
        for i in range(size):
            self.__pool.put(MySQLdb.connect(*args, **kwargs))
        # 创建一个local对象
        self.local = threading.local()
    @property
    def connect(self):
        return self.__pool.get()
    @connect.setter
    def connect(self, conn):
        self.__pool.put(conn)
    def __enter__(self):
        if getattr(self.local, 'conn', None) is None:
            self.local.conn = self.connect
        return self.local.conn.cursor()
    def __exit__(self, *exc_info):
        if exc_info:
            self.local.conn.rollback()
        else:
            self.local.conn.commit()
        # 将连接对象归还到连接池
        self.connect = self.local.conn
        # 线程级别的连接对象引用计算器减一
        self.local.conn = None
if __name__ == '__main__':
    pool = ConnectPool(host='localhost',
                       user='robby',
                       password='robby123456',
                       database='XKD_Python_Course',
                       use_unicode=True,
                       charset='utf8')
    def foo(pool):
        with pool as cursor:
            with cursor:  # 对cursor做上下文管理
                sql = 'select * from students'
                cursor.execute(sql)
                print(cursor.fetchall())
    for i in range(5):
        t = threading.Thread(target=foo, args=(pool, ))
        t.start()

11.queue模块中的Queue与multiprocessing模块的Queue的区别

参考:https://www.9xkd.com/user/plan-view.html?id=2546175346

上一篇 下一篇

猜你喜欢

热点阅读