Python 的数据库接口标准是 Python DB-API
PyMySQL 是从 Python 连接到 MySQL 数据库服务器的接口
PyMySQL 的目标是成为 MySQLdb 的替代品
官方文档:http://pymysql.readthedocs.io/
使用 pip 安装 pip install pymysql
使用 Pycharm 界面安装
# 1.导入库 import pymysql # 2.建立连接 conn = pymysql.connect(host='服务器地址', user='用户名', password='密码', database='数据库名', charset="utf8mb4") # 3.关闭连接 conn.close()
import pymysql # 1.封装建立连接的对象 def get_conn(): conn = pymysql.connect( host="服务器地址", user="root", password="123456", database="数据库名", charset="utf8mb4" ) return conn
from . import get_conn def test_demo(): # 1.获取连接对象 conn = get_conn() # 2.获取游标对象 cursor = conn.cursor() # 3.执行SQL cursor.execute("SELECT VERSION()") # 4.查询结果 version = cursor.fetchone() print(f"数据库的版本是:{version}") # 5.关闭连接 conn.close()
testcase
from . import get_conn def test_create(): conn = get_conn() # 获取连接 cursor = conn.cursor() # 获取游标 sql = """ CREATE TABLE `testcase` ( `id` int(11) NOT NULL AUTO_INCREMENT, `title` varchar(255) COLLATE utf8_bin NOT NULL, `expect` varchar(255) COLLATE utf8_bin NOT NULL, `owner` varchar(255) COLLATE utf8_bin NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin; """ cursor.execute(sql) # 执行SQL conn.close() # 关闭连接
from . import get_conn def test_insert(): conn = get_conn() # 获取连接 cursor = conn.cursor() # 获取游标 sql = """INSERT INTO testcase (id, title, expect, owner) values (1, 'S11总决赛', '冠军', 'EDG'); """ cursor.execute(sql) # 执行SQL conn.commit() # 提交
commit()
rollback()
try-catch-finally
from . import get_conn def test_insert(): conn = get_conn() # 获取连接 cursor = conn.cursor() # 获取游标 sql = """INSERT INTO testcase (id, title, expect, owner) values (2, 'S11全球总决赛', '冠军', 'EDG'); """ try: cursor.execute(sql) # 执行SQL conn.commit() # 提交事务 except: conn.rollback() # 回滚事务 finally: conn.close() # 关闭连接
fetchone()
:获取单条记录fetchmany(n)
:获取 n 条记录fetchall()
:获取所有结果记录import sys from . import get_conn def test_retrieve(): conn = get_conn() # 获取连接 cursor = conn.cursor() # 获取游标 sql = "SELECT * FROM testcase;" # 捕获异常 try: cursor.execute(sql) # 执行SQL record = cursor.fetchone() # 查询记录 print(record) except Exception as e: print(sys.exc_info()) # 打印错误信息 finally: conn.close() # 关闭连接
from . import get_conn def test_update(): conn = get_conn() cursor = conn.cursor() sql = "UPDATE testcase SET owner='hogwarts' WHERE id=2;" try: cursor.execute(sql) # 执行SQL conn.commit() # 提交事务 except: conn.rollback() # 回滚事务 finally: conn.close() # 关闭连接
from . import get_conn def test_delete(): conn = get_conn() # 获取连接 cursor = conn.cursor() # 获取游标 sql = "DELETE FROM testcase WHERE id=3;" try: cursor.execute(sql) # 执行SQL conn.commit() # 提交事务 except: conn.rollback() # 回滚事务 finally: conn.close() # 关闭连接