# -*- coding: utf-8 -*-
"""
Created on Sun May 5 19:32:35 2019
@author: ACERpython
windows中python3.6链接mysql,首先必须安装mysql插件,步骤以下:
打开cmd进入python3安装目录下的script目录
输入命令python pip.exe install pyMysql
出现successfully installed pyMysql*** 即安装成功
在cmd交互模式下输入import pymysql进行检测,若安装不成功会报错
将pymysql的包导入到Spyder中
在anaconda中找到Anaconda Prompt,单击右键,更多-->以管理员身份运行
输入pip list 能够查看已经附加的包
输入conda install pyMysql 回车便可
"""mysql
import pymysql as mysqlsql
# 打开数据库链接
db = mysql.connect("127.0.0.1", "root", "a", "usersys", charset='utf8' )数据库
# 使用cursor()方法获取操做游标
cursor = db.cursor()windows
# 若是数据表存在则删除。
cursor.execute("drop table if exists roles")fetch
# 建立数据表SQL语句
sql = """create table roles (
rid int primary key auto_increment,
rname varchar(100) not null unique,
status int
)"""插件
# 执行建立
cursor.execute(sql)ip
# 添加数据语句
sql = """insert into roles values(0,'%s', %d)""" %('超级管理员', 1)utf-8
try:
# 执行添加操做
cursor.execute(sql)
# 提交到数据库执行
db.commit()
if cursor.rowcount > 0:
print("角色信息添加成功")
else:
print("角色信息添加失败")
except:
# 若是添加失败,则回滚
db.rollback()
# 执行查询
cursor.execute("select rid, rname, status from roles order by rid")rem
# 抓取全部数据
data = cursor.fetchall();
for row in data:
print(row)
# 关闭数据库链接 db.close()