python操作mysql教程
时间: 2024-02-04 10:02:50 浏览: 95
首先,你需要安装Python的MySQL驱动程序,可以使用`pip`命令来安装,如下所示:
```
pip install mysql-connector-python
```
接下来,你需要连接到你的MySQL数据库,可以使用以下代码:
```python
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
print(mydb)
```
在这个代码中,你需要将`host`,`user`,`password`和`database`替换成你的MySQL数据库的实际值。如果一切正常,它将输出一个MySQL连接对象。
有了连接,你就可以执行SQL查询和操作了。以下是一些常见的操作:
1. 查询数据
```python
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM yourtable")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
```
这个代码将从`yourtable`表中选择所有数据,并打印出来。
2. 插入数据
```python
mycursor = mydb.cursor()
sql = "INSERT INTO yourtable (column1, column2, column3) VALUES (%s, %s, %s)"
val = ("value1", "value2", "value3")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
```
这个代码将向`yourtable`表中插入一条数据,并输出插入的记录数。
3. 更新数据
```python
mycursor = mydb.cursor()
sql = "UPDATE yourtable SET column1 = 'newvalue' WHERE id = 1"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) affected")
```
这个代码将更新`yourtable`表中`id`为1的行的`column1`列的值,并输出受影响的记录数。
4. 删除数据
```python
mycursor = mydb.cursor()
sql = "DELETE FROM yourtable WHERE id = 1"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) deleted")
```
这个代码将删除`yourtable`表中`id`为1的行,并输出删除的记录数。
这些是一些基本的Python操作MySQL的代码示例,你可以通过这些示例来快速入门。
阅读全文
相关推荐

















