pip install pymysql
# 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
获取连接对象
打开
关闭
获取游标对象
执行 SQL
查询记录
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() # 关闭连接
最后感谢每一个认真阅读我文章的人,礼尚往来总是要有的,虽然不是什么很值钱的东西,如果你用得到的话可以直接拿走:
这些资料,对于【软件测试】的朋友来说应该是最全面最完整的备战仓库,这个仓库也陪伴上万个测试工程师们走过最艰难的路程,希望也能帮助到你!