import mysql.connector
# 创建与MySQL数据库的连接
def create_connection():
try:
connection = mysql.connector.connect(
host='localhost', # 数据库主机地址
user='your_username', # 数据库用户名
password='your_password', # 数据库密码
database='your_database' # 要连接的数据库名称
)
if connection.is_connected():
print("成功连接到 MySQL 数据库")
return connection
except mysql.connector.Error as err:
print(f"连接失败: {err}")
return None
# 关闭数据库连接
def close_connection(connection):
if connection.is_connected():
connection.close()
print("MySQL 连接已关闭")
# 示例查询
def query_example(connection):
cursor = connection.cursor()
cursor.execute("SELECT * FROM your_table") # 替换为你的表名
rows = cursor.fetchall()
for row in rows:
print(row)
if __name__ == "__main__":
conn = create_connection()
if conn:
query_example(conn)
close_connection(conn)
mysql.connector 是用于连接和操作 MySQL 数据库的 Python 模块。create_connection 函数用于建立与 MySQL 数据库的连接。你需要提供主机地址、用户名、密码和数据库名称。close_connection 函数用于关闭与数据库的连接,确保资源释放。query_example 函数演示了如何执行一个简单的 SQL 查询并打印结果。__main__ 块中,首先创建连接,然后执行查询,最后关闭连接。请根据实际情况修改代码中的 host, user, password, database 和 your_table 等参数。
上一篇:mysql format
下一篇:mysql允许其他ip访问数据库
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站