python 操作MySQL
安装pymysql模块
pip install pymysql
(1) 连接MySQL数据库
pymysql.connect("主机名","用户名","密码","数据库名");
(2) 设置字符集
db.set_charset('utf8')
(3) 创建游标对象
cursor = db.cursor()
(4) 准备sql语句
(5) 执行sql语句
cursor.execute(sql)
(6) 处理结果集
cursor.fetchall(); # 获取所有数据 返回元组
cursor.fetchone(); # 获取一条数据
cursor.fetchmany(size) # 获取size条
(7) 当前sql语句执行受影响的行数
cursor.rowcount
(8) 关闭数据库连接
db.close() #
拼凑成正常sql语句的办法
sql = 'select id from type where typename ="{}"'.format(typeName) sql = 'select id from type where typename ="%s"'%(typeName) sql = 'select id from type where typename ="'+typeName+'"' sql = 'select id from type where typename =\''+typeName+'\''