pymysql
安装 :
- 在线 :sudo pip3 install pymysql
- 离线 :pymysql.tar.gz
解压:setup.py
python3 setup.py install
pymysql使用流程
- 建立数据库连接对象(db=pymysql.connect("root".
- 创建游标对象cur(操作数据库的对象)
- 游标对象:cur.execute("insert into sheng ...;")
- 提交到数据库执行 :db.commit()
- 关闭游标对象cur.close()
- 关闭数据库连接对象db.close()
示例 pymysql增删改
import pymysql
db = pymysql.connect(host="localhost",
user="root",password="123456",
database="db4",charset="utf8")
cursor = db.cursor()
try:
# 1.在sheng表中插入1条记录
sql_insert = 'insert into sheng(s_name) values("湖北省");'
cursor.execute(sql_insert)
# 2.在sheng表中删除id为8的记录
sql_delete = 'delete from sheng where id=8;'
cursor.execute(sql_delete)
# 3.在sheng表中把id为1的记录的省名改为 浙江省
sql_update = 'update sheng set s_name="浙江省" where id=1;'
cursor.execute(sql_update)
# 都执行成功再提交
db.commit()
print("ok")
except Exception as e:
db.rollback()
print("Failed",e)
cursor.close()
db.close()
示例2 SQL语句参数化
import pymysql
db = pymysql.connect(host="localhost",
user="root",password="123456",
database="db4",charset="utf8")
cursor = db.cursor()
try:
s_name = input("请输入省份:")
s_id = input("请输入该省编号:")
sql_insert = 'insert into sheng(s_name,s_id) \
values(%s,%s);'
L = [s_name,s_id]
cursor.execute(sql_insert,L) #此处必须用列表传参
db.commit()
print("ok")
except Exception as e:
db.rollback()
print("Failed",e)
cursor.close()
db.close()
- db = pymysql.connect(参数列表)
- host :主机地址
- user :用户名
- password :密码
- database :库
- charset :编码方式,推荐utf8
- port :端口(3306)
- db (数据库连接对象) 的方法
- db.close() :断开连接
- db.commit() :提交到数据库执行
- db.cursor() :游标对象,用来执行SQL命令
- db.rollback() :回滚
- cursor 游标对象 的方法
- execute(SQL命令) :执行SQL命令
- close() :关闭游标对象
- fetchone() :获取查询结果的第1条数据
- fetchmany(n) :获取n条数据
- fetchall() :获取所有数据
## fetchmany(n) 和 fetchall() 得到的结果一定是一个大元组套着小元组 ((),(),())
WorkBench 图形化界面管理工具
Navicat : Windows中图形化界面管理工具
orm(Object Relation Mapping) 对象关系映射
- 示例
import sqlalchemy
class User:
__tablename__ = "t1"
id = Column(Integer,primary_key=True)
name = Column(String(20))
解释:
一个类 User --> 数据库1张表
表中2个字段 :id 和 name