1小时学会 Python操作Mysql数据库之pymysql模块技术:https://www.bilibili.com/video/BV1Dz4y1j7Jr
通过pymysql的Connection类创建数据库连接,用完一定要关闭连接。
from pymysql import Connection
# 创建数据库连接
con = Connection(
host="localhost", # 主机名
port=3306, # 端口
user="root", # 账户
password="123456" # 密码
)
print(type(con))
print(con.get_host_info())
print(con.get_server_info())
# 关闭连接
con.close()
运行输出:
<class 'pymysql.connections.Connection'>
socket localhost:3306
5.7.18-log
改进,可能会出现异常,我们加上 try except finally
from pymysql import Connection
con = None
try:
# 创建数据库连接
con = Connection(
host="localhost", # 主机名
port=3306, # 端口
user="root", # 账户
password="123456" # 密码
)
print(type(con))
print(con.get_host_info())
print(con.get_server_info())
except Exception as e:
print("异常:", e)
finally:
if con:
# 关闭连接
con.close()