使用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()

 

相关文章:

  • 2022-01-14
  • 2021-08-01
  • 2021-09-28
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-21
  • 2021-09-24
  • 2021-12-20
  • 2018-04-27
相关资源
相似解决方案