import mysql.connector
# 创建数据库连接
def connect_to_database():
try:
# 连接参数
connection = mysql.connector.connect(
host='localhost', # 数据库主机地址
user='your_username', # 数据库用户名
password='your_password', # 数据库密码
database='your_database' # 要连接的数据库名称
)
if connection.is_connected():
print("成功连接到数据库")
return connection
except mysql.connector.Error as err:
print(f"连接失败: {err}")
return None
# 示例使用
db_connection = connect_to_database()
if db_connection:
# 在这里可以执行查询等操作
db_connection.close() # 使用完毕后关闭连接
mysql.connector 模块,用于与 MySQL 数据库进行交互。connect_to_database 的函数,用于建立与 MySQL 数据库的连接。mysql.connector.connect() 方法传入连接所需的参数,包括主机地址、用户名、密码和数据库名称。try-except 结构捕获连接过程中可能出现的异常,并打印错误信息。None。connect_to_database 函数获取连接对象,并在使用完毕后关闭连接。上一篇:mysql删除重复项只保留一条
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站