1. Flask 数据库连接

Flask 数据库连接

初级阶段

import pymysql
from flask import Flask

app = Flask(__name__)

def fetchall(sql):
    conn = pymysql.connect(host='home.vimll.com', port=xxxxxx, user='python', passwd='xxxxxx', db='test')
    cursor = conn.cursor()
    cursor.execute(sql)
    result = cursor.fetchall()
    cursor.close()
    conn.close()
    return result

@app.route('/login')
def login():
    result = fetchall('select * from employees')
    return 'login'

@app.route('/index')
def index():
    result = fetchall('select * from employees')
    return 'xxx'

@app.route('/order')
def order():
    result = fetchall('select * from `order`')
    print(result)
    return 'xxx'

if __name__ == '__main__':
    app.run()
* Serving Flask app '__main__'
 * Debug mode: off

WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on http://127.0.0.1:5000
Press CTRL+C to quit
127.0.0.1 - - [14/May/2024 09:32:04] "GET /order HTTP/1.1" 200 -

((1, 'shkstart'), (2, 'tomcat'), (3, 'dubbo'))

中级阶段

import pymysql
from flask import Flask

app = Flask(__name__)

CONN = pymysql.connect(host='home.vimll.com', port=xxxxxx, user='python', passwd='xxxxxx', db='test')

def fetchall(sql):
    cursor = CONN.cursor()
    cursor.execute(sql)
    result = cursor.fetchall()
    cursor.close()
    return result

@app.route('/login')
def login():
    result = fetchall('select * from user')
    return 'login'

@app.route('/index')
def index():
    result = fetchall('select * from user')
    return 'xxx'

@app.route('/order')
def order():
    result = fetchall('select * from user')
    return 'xxx'

if __name__ == '__main__':
    app.run()

数据库连接池

  • pip3 install dbutils
  • pip3 install pymysql
import pymysql
# from DBUtils.PooledDB import PooledDB
from dbutils.pooled_db import PooledDB

POOL = PooledDB(
    creator=pymysql,  # 使用链接数据库的模块
    maxconnections=500,  # 连接池允许的最大连接数,0和None表示不限制连接数
    mincached=5,  # 初始化时,链接池中至少创建的链接,0表示不创建
    blocking=True,  # 连接池中如果没有可用连接后,是否阻塞等待。True,等待;False,不等待然后报错
    ping=0, # ping MySQL服务端,检查是否服务可用。# 如:0 = None = never, 1 = default = whenever it is requested, 2 = when a cursor is created, 4 = when a query is executed, 7 = always

    host='home.vimll.com',
    port=xxxxxx,
    user='python',
    password='xxxxxx',
    database='test',
    charset='utf8'
)

# 去连接池中获取一个连接
conn = POOL.connection()

cursor = conn.cursor()
cursor.execute('select * from `order`')
result = cursor.fetchall()
cursor.close()

# 将连接放会到连接池
conn.close()

print(result)
((1, 'shkstart'), (2, 'tomcat'), (3, 'dubbo'))

多线程连接测试

from threading import Thread
import pymysql
from dbutils.pooled_db import PooledDB

POOL = PooledDB(
    creator=pymysql,  # 使用链接数据库的模块
    maxconnections=20,  # 连接池允许的最大连接数,0和None表示不限制连接数
    mincached=5,  # 初始化时,链接池中至少创建的链接,0表示不创建
    blocking=True,  # 连接池中如果没有可用连接后,是否阻塞等待。True,等待;False,不等待然后报错
    ping=0,  # ping MySQL服务端,检查是否服务可用。# 如:0 = None = never, 1 = default = whenever it is requested, 2 = when a cursor is created, 4 = when a query is executed, 7 = always

    host='home.vimll.com',
    port=xxxxxx,
    user='python',
    password='xxxxxx',
    database='test',
    charset='utf8'
)

def task(num, sql):
    # 去连接池中获取一个连接
    conn = POOL.connection()
    cursor = conn.cursor()
    # cursor.execute('select * from `order`')
    # cursor.execute('select sleep(3)')
    cursor.execute(sql)
    result = cursor.fetchall()
    cursor.close()

    conn.close()   # 将连接放会到连接池
    print(num, '------------>', result)

for i in range(50):
    sql = 'select * from `order`;'
    t = Thread(target=task, args=(i, sql))
    t.start()

基于函数实现sqlhelper

./sqlhelper.py

import pymysql
# from DBUtils.PooledDB import PooledDB
from dbutils.pooled_db import PooledDB

POOL = PooledDB(
    creator=pymysql,  # 使用链接数据库的模块
    maxconnections=6,  # 连接池允许的最大连接数,0和None表示不限制连接数
    mincached=2,  # 初始化时,链接池中至少创建的链接,0表示不创建
    blocking=True,  # 连接池中如果没有可用连接后,是否阻塞等待。True,等待;False,不等待然后报错
    ping=0, # ping MySQL服务端,检查是否服务可用。# 如:0 = None = never, 1 = default = whenever it is requested, 2 = when a cursor is created, 4 = when a query is executed, 7 = always

    host='home.vimll.com',
    port=xxxxxx,
    user='python',
    password='xxxxxx',
    database='test',
    charset='utf8'
)

def fetchall(sql,*args):
    """ 获取所有数据 """
    conn = POOL.connection()
    cursor = conn.cursor()
    cursor.execute(sql,args)
    result = cursor.fetchall()
    cursor.close()
    conn.close()

    return result

def fetchone(sql, *args):
    """ 获取单条数据 """
    conn = POOL.connection()
    cursor = conn.cursor()
    cursor.execute(sql, args)
    result = cursor.fetchone()
    cursor.close()
    conn.close()

    return result
from flask import Flask
import sqlhelper

app = Flask(__name__)

@app.route('/login')
def login():
    result = sqlhelper.fetchone('select * from `order` where order_id=%s;','1')
    print(result)
    return 'login'

@app.route('/index')
def index():
    result = sqlhelper.fetchall('select * from `order`')
    print(result)
    return 'xxx'

@app.route('/order')
def order():
    # result = fetchall('select * from user')
    return 'xxx'

if __name__ == '__main__':
    app.run()

基于类实现sqlhelper

./sqlhelper2.py

import pymysql
from dbutils.pooled_db import PooledDB

class SqlHelper(object):
    def __init__(self):
        self.pool = PooledDB(
            creator=pymysql,  # 使用链接数据库的模块
            maxconnections=6,  # 连接池允许的最大连接数,0和None表示不限制连接数
            mincached=2,  # 初始化时,链接池中至少创建的链接,0表示不创建
            blocking=True,  # 连接池中如果没有可用连接后,是否阻塞等待。True,等待;False,不等待然后报错
            ping=0,
            # ping MySQL服务端,检查是否服务可用。# 如:0 = None = never, 1 = default = whenever it is requested, 2 = when a cursor is created, 4 = when a query is executed, 7 = always
            host='home.vimll.com',
            port=xxxxxx,
            user='python',
            password='xxxxxx',
            database='test',
            charset='utf8'
        )

    def open(self):
        """创建连接"""
        conn = self.pool.connection()
        cursor = conn.cursor()
        return conn, cursor

    def close(self, cursor, conn):
        """关闭连接"""
        cursor.close()
        conn.close()

    def fetchall(self, sql, *args):
        """ 获取所有数据 """
        conn, cursor = self.open()
        cursor.execute(sql, args)
        result = cursor.fetchall()
        self.close(conn, cursor)
        return result

    def fetchone(self, sql, *args):
        """ 获取一条数据 """
        conn, cursor = self.open()
        cursor.execute(sql, args)
        result = cursor.fetchone()
        self.close(conn, cursor)
        return result

    def fetchmany(self, sql, *args, num=1):
        """ 获取指定多少条数据 """
        conn, cursor = self.open()
        cursor.execute(sql, args)
        result = cursor.fetchmany(size=num)
        self.close(conn, cursor)
        return result

# 在这里生成一个对象,外表调用自然是单例模式
db = SqlHelper()

if __name__ == '__main__':
    from sqlhelper2 import db
    result = db.fetchone('select * from `order` where order_id=%s;', '1')
    print(result)
    result1 = db.fetchall('select * from `order`;')
    print(result1)
    result2 = db.fetchmany('select * from `order`;', num=2)
    print(result2)
from flask import Flask
from sqlhelper2 import db

app = Flask(__name__)

@app.route('/login')
def login():
    result = db.fetchone('select * from `order` where order_id=%s;', '1')
    print(result)
    return 'login'

@app.route('/all')
def all():
    result = db.fetchall('select * from `order`;')
    print(result)
    return 'xxx'

@app.route('/index')
def index():
    result = db.fetchmany('select * from `order`;', num=2)
    print(result)
    return 'xxx'

@app.route('/order')
def order():
    # db.fetchall()
    conn, cursor = db.open()
    # 自己做操作
    cursor.execute('select * from `order` where order_id=%s;', '1')
    result = cursor.fetchone()
    print(result)
    db.close(conn, cursor)
    return 'xxx'

if __name__ == '__main__':
    app.run()
* Serving Flask app '__main__'
 * Debug mode: off

WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on http://127.0.0.1:5000
Press CTRL+C to quit
127.0.0.1 - - [14/May/2024 13:56:15] "GET /index HTTP/1.1" 200 -

((1, 'shkstart'), (2, 'tomcat'))

上下文管理和sqlhelper

import pymysql
from dbutils.pooled_db import PooledDB

class SqlHelper(object):
    def __init__(self):
        self.pool = PooledDB(
            creator=pymysql,
            maxconnections=6,
            mincached=2,
            blocking=True,
            ping=0,

            host='home.vimll.com',
            port=xxxxxx,
            user='python',
            password='xxxxxx',
            database='test',
            charset='utf8'
        )

    def open(self):
        """创建连接"""
        conn = self.pool.connection()
        cursor = conn.cursor()
        return conn, cursor

    def close(self, cursor, conn):
        """关闭连接"""
        cursor.close()
        conn.close()

    def fetchall(self, sql, *args):
        """ 获取所有数据 """
        conn, cursor = self.open()
        cursor.execute(sql, args)
        result = cursor.fetchall()
        self.close(conn, cursor)
        return result

    def fetchone(self, sql, *args):
        """ 获取一条数据 """
        conn, cursor = self.open()
        cursor.execute(sql, args)
        result = cursor.fetchone()
        self.close(conn, cursor)
        return result

    def fetchmany(self, sql, *args, num=1):
        """ 获取指定多少条数据 """
        conn, cursor = self.open()
        cursor.execute(sql, args)
        result = cursor.fetchmany(size=num)
        self.close(conn, cursor)
        return result

db = SqlHelper()

if __name__ == '__main__':
    from sqlhelper2 import db
    result = db.fetchone('select * from `order` where order_id=%s;', '1')
    print(result)
    result1 = db.fetchall('select * from `order`;')
    print(result1)
    result2 = db.fetchmany('select * from `order`;', num=2)
    print(result2)
from flask import Flask
from sqlhelper3 import db

app = Flask(__name__)

@app.route('/login')
def login():
    result = db.fetchone('select * from `order` where order_id=%s;', '1')
    print(result)
    return 'login'

@app.route('/all')
def all():
    result = db.fetchall('select * from `order`;')
    print(result)
    return 'xxx'

@app.route('/index')
def index():
    result = db.fetchmany('select * from `order`;', num=2)
    print(result)
    return 'xxx'

@app.route('/order')
def order():
    # db.fetchall()
    conn, cursor = db.open()
    # 自己做操作
    cursor.execute('select * from `order` where order_id=%s;', '1')
    result = cursor.fetchone()
    print(result)
    db.close(conn, cursor)
    return 'xxx'

@app.route('/test')
def test():

    with db as cur:
        cur.execute('select * from `order` where order_id=%s;', '1')
        with db as cur2:
            cur2.execute('select * from `order` where order_id=%s;', '2')

            result = cur.fetchone()
            result2 = cur2.fetchone()

        return 'xxx'

if __name__ == '__main__':
    app.run()
* Serving Flask app '__main__'
 * Debug mode: off

WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on http://127.0.0.1:5000
Press CTRL+C to quit
127.0.0.1 - - [14/May/2024 14:18:38] "GET /all HTTP/1.1" 200 -

((1, 'shkstart'), (2, 'tomcat'), (3, 'dubbo'))

127.0.0.1 - - [14/May/2024 14:18:48] "GET /index HTTP/1.1" 200 -

((1, 'shkstart'), (2, 'tomcat'))

127.0.0.1 - - [14/May/2024 14:18:56] "GET /test HTTP/1.1" 200 -

(1, 'shkstart')
None None None