摘要
- 导入模块
- 对数据库的增删改查
1.导入模块,进入mysql
import pymysql
db = pymysql.Connect(user='root',passwd='***')
cur = db.cursor()
#cursor为控制游标
2.创建删除库
sql = 'create database guoguo'
#创建名字为guoguo的库
sql = 'drop database guoguo'
#删除库
sql = 'show databases'
#查看现有数据库(文件夹)
sql = ' use guoguo'
#进入guoguo的库
cur.excute(sql) #即为执行该操作
3.创建table
- 数值型 int
- 小数型 decimal(m,d)
- 字符串 varchar(5) 非定长的字符串
- 时间性 timestamp 时间戳
sql =
"""
create table user(
id int unsigned not null auto_increment comment '用户id',
user_name varchar(20) not null comment '用户名',
age tinyint unsigned not null comment '用户年龄',
fee decimal(10,2) not null default 0.00 comment '用户余额',
created_at timestamp not null comment '注册时间',
primary key(id)
)
"""
# 名字 类型 性质(not null) 是否自增 comment ''
sql = 'show tables'
#查看所有的tables(excel)
sql = 'desc guoguo'
#查看guoguo(excel中的表头)
try:
cur.excute(sql)
db.commit()
except:
db.rollback()
#发生错误时回滚
db.close
#关闭数据库
4.增删改查
#增加
sql = " insert into guoguo( \
first_name, last_name, id, gender) \
values (%s,%s,%s,%s) " \
%('G','guoguo',2170,'female')
# insert into guoguo (名字) values (数据)
#删除
sql = " drop table guoguo"
sql = "delete from guoguo where id = %s"%(2170)
#删除excel用drop,删除内容用delete
#改变
sql = "alter table guoguo rename to guoguos"
sql = "alter table guoguo modify first_name varchar(50)"
sql = "update guoguo set age = %s where id in (2,3,5)"%(20)
#改变excel的名字和性质用alter rename/ modify 改变excel里面的内容
#查询
sql = "select * from guoguo where age >= 25"
try:
cursor.execute(sql)
# 获取所有记录列表
results = cursor.fetchall() #fetchone和fetchall
for row in results:
fname = row[0]
lname = row[1]
age = row[2]
gender = row[3]
income = row[4]
# 打印结果
print ("fname=%s,lname=%s,age=%s,gender=%s,income=%s" % \
(fname, lname, age, sex, income ))
except:
print ("Error: unable to fetch data")
db.close()
网友评论