pymysql 简单操作数据库

#!/usr/bin/env python
#-*- coding:utf-8 -*-
# author:leo
# datetime:2019/4/24 15:22
# software: PyCharm
#pymysql 数据库操作
import pymysql
#配置信息
config={"host":"127.0.0.1","user":"root","password":"root","database":"leocms","charset":"utf8","port":3306}
#设置查出为字点
#config={"host":"127.0.0.1","user":"root","password":"root","database":"leocms","charset":"utf8","port":3306,"cursorclass": pymysql.cursors.DictCursor}
#链接数据库,建立链接
client=pymysql.connect(**config)
#获取游标
cursors=client.cursor()
sql="show tables"
#显示数据库所有的数据表
cursors.execute(sql)
for one in cursors:
print(one) #返回元祖
cursors.close()#关闭游标
#插入数据
cursors=client.cursor()
sql="INSERT INTO leo_user (`username`,`password`) VALUES (%s,%s)"
username=input("用户》》").strip()
password=input("密码》》").strip()
cursors.execute(sql,(username,password))
cursors.close()
client.commit()#提交事务
#修改数据
cursors=client.cursor()
sql="UPDATE leo_user SET `username`=%s,`password`=%s WHERE uid=%s"
id=input("你要修改给的ID》》")
username=input("用户名>>").strip()
password=input("密码》》").strip()
cursors.execute(sql,(username,password,id))
cursors.close()
client.commit()
#查询数据
cursors=client.cursor(pymysql.cursors.DictCursor)#查出数据为字典 ;不加pymysql.cursors.DictCursor 为元祖
sql="SELECT * FROM leo_user"
cursors.execute(sql)
for one in cursors:
print(one)
cursors.close()
client.close()
上一篇:pandas中遍历dataframe的每一个元素


下一篇:React props传变量