首页 > 技术文章 > python 操作数据库

mlllily 2019-07-24 15:03 原文

使用Python操作MySQL数据库这里我们需要用到三方库PyMySQl

安装方法:pip install pymysql

import pymysql

# 1. 建立连接
conn = pymysql.connect(host='127.0.0.1',
                    port=3306,
                    user='root',
                    passwd='123456',   # password也可以
                    db='api_test',
                    charset='utf8')   # 如果查询有中文需要指定数据库编码
                    
# 2. 从连接建立游标(有了游标才能操作数据库)
cursor = conn.cursor()

# 3. 查询数据库(读)
cursor.execute("select * from user where name='张三'")

# 4. 获取查询结果
result = cursor.fetchall()

# 4. 提交更改
conn.commit()  # 注意是用的conn不是cursor

# 5. 关闭游标及连接
cursor.close()
conn.close()

 

推荐阅读