前期准备
安装pymysql
通过cmd命令行执行如下命令
pip install pymysql
数据库操作
连接
#导入pymysql模块
import pymysql
#创建一个连接
cn = pymysql.connect("localhost", "root", "******", "test")
# 数据库地址, 用户名 , 密码 , 要连接的数据库
# 使用cursor方法创建一个游标对象
cs = cn.cursor()
# 关闭游标对象
cs.close()
# 关闭连接
cn.close()
查询
# 这里写sql语句结束时不需要添加 ";"
sql = "select * from test"
# 执行sql语句
cs.execute(sql)
'''
移动光标
1.scroll(index) # 默认是相对移动
2.scroll(index, mode='absolute') # 按照绝对位置移动
获取数据的形式:
1.获取单条数据 fetchone()
2.获取全部数据 fetchall()
3.获取指定条目 fetchmany(number)
返回值类型为元组
'''
try:
# 获取单条数据
res = cs.fecthone()
print(res)
# 将指针定位至起始位置
cs.scroll(0)
# 获取所有数据
result = cs.fethall()
for row in result:
id = row[0]
name = row[1]
print("ID:{},NAME:{}.format(id,name)")
增删改
# 创建一张数据表
sql_create = "create talbe demo(id int primary key not null, name varchar(20) not null)"
cs.exectue(sql_create)
# 增加数据
sql_in = "insert into demo values(1,'java'),(2,'python')"
# 更新数据
# sql_up = "update demo set name='C' where id = 1"
# 删除数据
# sql_del = "delete from demo where id=2"
try:
cs.execute(sql_in)
# cs.execute(sql_up)
# cs.execute(sql_del)
# 提交到数据库执行
cn.commit()
except:
# 发生错误执行回滚
cn.rollback()