连接mysql数据库代码

在Python中连接MySQL数据库通常使用mysql-connector-python库。首先,你需要安装这个库,可以使用pip进行安装:

pip install mysql-connector-python

接下来,

python
import mysql.connector # 连接MySQL数据库 try: connection = mysql.connector.connect( host='your_host', user='your_username', password='your_password', database='your_database_name' ) if connection.is_connected(): db_Info = connection.get_server_info() print("Connected to MySQL Server version ", db_Info) cursor = connection.cursor() cursor.execute("select database();") record = cursor.fetchone() print("You're connected to database: ", record) except mysql.connector.Error as e: print("Error while connecting to MySQL", e) # 关闭连接 finally: if connection.is_connected(): cursor.close() connection.close() print("MySQL connection is closed")

在这个示例中:

替换your_hostyour_usernameyour_passwordyour_database_name为你的实际数据库主机、用户名、密码和数据库名称。mysql.connector.connect()方法用于建立与MySQL数据库的连接。通过connection.cursor()创建一个游标对象,用于执行SQL查询。最后,别忘记在完成操作后关闭数据库连接。

这是一个基本的示例,你可以根据自己的需求进行调整和扩展。

当连接成功建立后,你可以执行各种操作,如执行SQL查询、插入、更新或删除数据等。

执行SQL查询

python
# 执行SQL查询 query = "SELECT * FROM your_table;" cursor.execute(query) rows = cursor.fetchall() for row in rows: print(row)

插入数据

python
# 插入数据 insert_query = "INSERT INTO your_table (column1, column2, column3) VALUES (%s, %s, %s);" data = ('value1', 'value2', 'value3') cursor.execute(insert_query, data) connection.commit() # Commit changes to the database print("Data inserted successfully")

更新数据

python
# 更新数据 update_query = "UPDATE your_table SET column1 = %s WHERE condition;" new_value = 'new_value' cursor.execute(update_query, (new_value,)) connection.commit() # Commit changes to the database print("Data updated successfully")

删除数据

python
# 删除数据 delete_query = "DELETE FROM your_table WHERE condition;" cursor.execute(delete_query) connection.commit() # Commit changes to the database print("Data deleted successfully")

记得在执行修改数据库的操作时,使用connection.commit()方法来提交事务,以确保更改生效。