1、创建测试数据库
use test;
CREATE TABLE `t_user` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`userName` VARCHAR(20) DEFAULT NULL,
`password` VARCHAR(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
INSERT INTO `t_user`(`id`,`userName`,`password`) VALUES (1,'小蜜蜂编程','123');
2、代码
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2024-07-23 11:19
# @Author : 小蜜蜂编程
from pymysql import Connection
def getConn():
"""
获取数据库连接
:return: 数据库连接
"""
conn=Connection(
host="localhost",
port=3306,
user='root',
password='123456',
database='test',
autocommit=True
)
return conn
def closeConn(conn:Connection):
"""
关闭数据库连接
:param conn: 数据库连接
:return:
"""
if conn:
conn.close()
if __name__=='__main__':
conn=None
try:
conn=getConn()
cursor=conn.cursor()
cursor.execute("select * from t_user")
print(cursor.fetchall())
except Exception as e:
print(e)
finally:
closeConn(conn)
3、结果