您的位置:宽带测速网 > 网络知识 > python连接mysql代码怎么写

python连接mysql代码怎么写

2025-06-16 12:28来源:互联网 [ ]

要使用Python连接MySQL数据库,您可以使用mysql-connector-python库。首先,确保您已经安装了该库。如果尚未安装,可以使用以下命令进行安装:

pip install mysql-connector-python

接下来,您可以使用以下代码示例来连接到MySQL数据库:

import mysql.connectordef connect_to_mysql_db(host, user, password, database):try:connection = mysql.connector.connect(host=host,user=user,password=password,database=database)print("成功连接到MySQL数据库")return connectionexcept mysql.connector.Error as error:print(f"连接失败,错误信息:{error}")return Nonedef close_mysql_connection(connection):if connection:connection.close()print("已关闭MySQL数据库连接")if __name__ == "__main__":# 替换以下信息为您自己的MySQL数据库信息host = "your_host"user = "your_user"password = "your_password"database = "your_database"# 连接到MySQL数据库mysql_connection = connect_to_mysql_db(host, user, password, database)# 在此处执行您的数据库操作,例如查询、插入、更新等# 关闭MySQL连接close_mysql_connection(mysql_connection)

请确保将your_hostyour_useryour_passwordyour_database替换为您自己的MySQL数据库信息。在此示例中,我们定义了一个名为connect_to_mysql_db的函数,该函数尝试连接到指定的MySQL数据库,并在成功连接时返回一个连接对象。我们还定义了一个名为close_mysql_connection的函数,用于关闭已打开的数据库连接。在__main__部分中,我们调用这些函数来连接到数据库、执行操作并关闭连接。