type
Post
status
Published
date
Jul 22, 2022
slug
article-7
summary
python中mysql操作
tags
Python
mysql
category
技术分享
icon
password
Property
Jul 22, 2022 03:19 PM

安装库

pip3 install pymysql

基本使用

import pymysql # 创建mysql连接对象 connection = pymysql.connect(host='localhost', port=3306, user='root', passwd='your_passwd', db='table_name', charset='utf8') # 创建游标对象 cursor = connection.cursor() # 执行sql语句 返回值为受影响的行数 print(cursor.execute("select * from school")) # 获取全部结果, 没有则返回空元组 print(cursor.fetchall()) # 获取1条结果, 没有则返回null print(cursor.fetchone()) # 获取指定数量结果, 没有则返回空元组 print(cursor.fetchmany(5)) # 提交 connection.commit() # 回滚 connection.rollback()
注意:
  • pymysql 默认处理事务, 因此插入修改等操作需要commit()
  • 如果sql/数据中存在中文, 则在连接对象创建时设置utf8编码
  • pymysql会将每次获取的结果在游标对象中被删除
执行过程:
  1. pymysql.connect() 获取数据库连接对象
  1. 通过 连接对象.cursor() 获取游标对象
  1. 通过 连接对象.execute(sql语句) 执行sql
  1. 执行sql的结果存储在游标对象中
  1. 通过游标对象中的 fetchall() fetchone() fetchmany(count) 方法获取结果
  1. 每次获取到的结果都会在游标对象中被删除
  1. 如果已经获取结果, 需要重新获取结果时, 回到过程1
 
MySql 树形结构表存储方案乘法逆元

  • Valine
  • Giscus