通过Python连接MySQL数据库,可以使用多种库来实现,以下是两种常见的方法:
使用mysql-connector-python
库
1、安装库:
```bash
pip install mysql-connector-python
```
2、连接到MySQL数据库:
```python
import mysql.connector
# 创建数据库连接
db = mysql.connector.connect(
host="localhost", # MySQL服务器地址
user="yourusername", # 用户名
password="yourpassword", # 密码
database="yourdatabase" # 数据库名称
)
# 创建游标对象
cursor = db.cursor()
```
3、执行SQL查询:
```python
# 执行查询
cursor.execute("SELECT * FROM yourtable")
# 获取查询结果
results = cursor.fetchall()
for row in results:
print(row)
```
4、插入数据:
```python
sql = "INSERT INTO yourtable (column1, column2) VALUES (%s, %s)"
values = ("value1", "value2")
cursor.execute(sql, values)
# 提交更改到数据库
db.commit()
```
5、更新和删除数据:
```python
# 更新数据
sql = "UPDATE yourtable SET column1 = %s WHERE column2 = %s"
values = ("newvalue", "value2")
cursor.execute(sql, values)
db.commit()
# 删除数据
sql = "DELETE FROM yourtable WHERE column1 = %s"
values = ("value1",)
cursor.execute(sql, values)
db.commit()
```
6、关闭连接:
```python
cursor.close()
db.close()
```
使用PyMySQL
库
1、安装库:
```bash
pip install PyMySQL
```
2、连接到MySQL数据库:
```python
import pymysql
# 创建数据库连接
db = pymysql.connect(host='localhost', user='yourusername', password='yourpassword', database='yourdatabase')
# 创建游标对象
cursor = db.cursor()
```
3、执行SQL查询:
```python
# 执行查询
cursor.execute("SELECT * FROM yourtable")
# 获取查询结果
results = cursor.fetchall()
for row in results:
print(row)
```
4、插入数据:
```python
sql = "INSERT INTO yourtable (column1, column2) VALUES (%s, %s)"
values = ("value1", "value2")
cursor.execute(sql, values)
# 提交更改到数据库
db.commit()
```
5、更新和删除数据:
```python
# 更新数据
sql = "UPDATE yourtable SET column1 = %s WHERE column2 = %s"
values = ("newvalue", "value2")
cursor.execute(sql, values)
db.commit()
# 删除数据
sql = "DELETE FROM yourtable WHERE column1 = %s"
values = ("value1",)
cursor.execute(sql, values)
db.commit()
```
6、关闭连接:
```python
cursor.close()
db.close()
```
本文来源于互联网,如若侵权,请联系管理员删除,本文链接:https://www.9969.net/61843.html