76 lines
1.1 KiB
Markdown
76 lines
1.1 KiB
Markdown
# python+sql
|
|
|
|
## python 中操作
|
|
|
|
```sh
|
|
pip install pymysql
|
|
```
|
|
|
|
```python
|
|
from pymysql import Connection
|
|
|
|
conn = Connection(
|
|
host="主机名或ip",
|
|
port=端口,
|
|
user="用户名",
|
|
password="密码"
|
|
)
|
|
|
|
# 打印信息
|
|
print(conn.get_server_info)
|
|
# 关闭连接
|
|
conn.close()
|
|
```
|
|
|
|
* 非查询性质的sql语句
|
|
|
|
```python
|
|
# 获取游标对象
|
|
cursor = conn.cursor()
|
|
# 选择数据库
|
|
conn.select_db("库名")
|
|
# 使用游标对象, 执行sql语句
|
|
cursor.execute("sql语句")
|
|
conn.close()
|
|
```
|
|
|
|
* 查询性质的语句
|
|
|
|
```python
|
|
cursor = conn.cursor()
|
|
conn.select_db("库名")
|
|
cursor.execute("sql查询语句")
|
|
# 获取查询结果
|
|
results: tuple = cursor.fetchall()
|
|
for r in results:
|
|
print(r)
|
|
conn.close()
|
|
```
|
|
|
|
* 修改
|
|
|
|
===数据库发生修改, 需要提交===
|
|
|
|
```python
|
|
# 获取游标对象
|
|
cursor = conn.cursor()
|
|
# 选择数据库
|
|
conn.select_db("库名")
|
|
# 使用游标对象, 执行sql语句
|
|
cursor.execute("修改操作语句")
|
|
# 需要提交
|
|
conn.commit()
|
|
conn.close()
|
|
```
|
|
|
|
或者设置自动提交
|
|
|
|
```python
|
|
conn = Connection(
|
|
host="主机名或ip",
|
|
port=端口,
|
|
user="用户名",
|
|
password="密码",
|
|
autocommit=True
|
|
)
|
|
``` |