Python操作mysql数据库
Python、操作、mysql、数据库
要在Python中操作MySQL数据库,需要先安装mysql-connector-python这个包,可以通过以下命令进行安装:
```
pip install mysql-connector-python
```
连接到MySQL数据库的步骤如下:
1. 导入mysql.connector模块
```python
import mysql.connector
```
2. 建立连接并创建游标对象
```python
mydb = mysql.connector.connect(
host="localhost",
user="username",
password="password",
database="database_name"
)
mycursor = mydb.cursor()
```
3. 执行SQL语句
```python
# 创建表
mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")
# 插入数据
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)
mydb.commit()
# 查询数据
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
```
最后,记得在使用完毕后关闭连接。
```python
mydb.close()
```
[[1](