# 导入MySQL连接库
import mysql.connector
# 创建数据库连接
def connect_to_mysql(host, user, password, database):
try:
# 建立连接
connection = mysql.connector.connect(
host=host, # 主机地址
user=user, # 用户名
password=password, # 密码
database=database # 数据库名称
)
if connection.is_connected():
print("成功连接到 MySQL 数据库")
return connection
except mysql.connector.Error as err:
print(f"连接失败: {err}")
return None
# 示例使用
if __name__ == "__main__":
# 替换为你的数据库信息
host = "192.168.1.100"
user = "root"
password = "your_password"
database = "your_database"
connection = connect_to_mysql(host, user, password, database)
if connection:
# 执行查询或操作
cursor = connection.cursor()
cursor.execute("SELECT DATABASE();")
result = cursor.fetchone()
print(f"当前数据库: {result}")
# 关闭连接
cursor.close()
connection.close()
mysql.connector
库,用于与 MySQL 数据库进行交互。connect_to_mysql
函数,接收主机地址、用户名、密码和数据库名称作为参数,并尝试建立连接。try-except
块捕获连接过程中可能出现的错误,并打印错误信息。None
。__main__
中提供了一个示例,展示如何调用 connect_to_mysql
函数并执行简单的查询操作。请根据实际情况替换代码中的主机地址、用户名、密码和数据库名称。
下一篇:mysql if exists
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站