Python 是一种广泛使用的编程语言,可以与 MySQL 数据库进行交互。MySQL 是一种流行的关系型数据库管理系统,常用于存储和管理大规模的数据。
Python 中有几个库可以与 MySQL 数据库进行交互,其中最常用的是 mysql-connector-python
。以下是使用 Python 连接 MySQL 数据库的基本步骤:
安装 mysql-connector-python:
bash复制代码pip install mysql-connector-python
在 Python 代码中导入 mysql-connector-python:
python复制代码import mysql.connector
建立与 MySQL 数据库的连接:
python复制代码mydb = mysql.connector.connect(host="localhost",user="yourusername",password="yourpassword",database="yourdatabase" )
创建游标对象并执行 SQL 查询:
python复制代码mycursor = mydb.cursor()mycursor.execute("SELECT * FROM yourtable")
获取查询结果:
python复制代码myresult = mycursor.fetchall()for x in myresult:print(x)
完整的示例代码如下:
python复制代码import mysql.connector
mydb = mysql.connector.connect( host="localhost", user="yourusername", password="yourpassword", database="yourdatabase" )
mycursor = mydb.cursor() mycursor.execute("SELECT * FROM yourtable")
myresult = mycursor.fetchall() for x in myresult: print(x)