Python pymysql
Posted 风流 少年
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python pymysql相关的知识,希望对你有一定的参考价值。
一:安装mysql库
pip install pymysql
二:基础示例
import pymysql
from pymysql.cursors import DictCursor
# 1.创建连接
# cursorclass: 全局定义,表示查询时是返回的数据类型,字典还是元组(默认)
conn = pymysql.connect(host='127.0.0.1',
port=3306,
user='root',
password='123456',
database='test',
charset='utf8',
cursorclass=DictCursor)
# 2.获取游标,局部定义cursor
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# 3.定义sql,最好使用"""来定义字符串,这样关键字会变色
create_table_sql = """
CREATE TABLE IF NOT EXISTS sys_user2 (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(15) NOT NULL COMMENT '用户名',
`gender` tinyint(3) unsigned DEFAULT '0' COMMENT '性别(0: 女 1:男)',
`amount` decimal(10,2) DEFAULT NULL,
`create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '注册时间',
PRIMARY KEY (`id`),
UNIQUE KEY `uk` (`username`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8
"""
# 4.执行
cursor.execute(create_table_sql)
delete_sql = """
delete from sys_user2
"""
cursor.execute(delete_sql)
insert_sql = """
insert into sys_user2(username, gender, amount, create_time) values(%s, %s, %s, now())
"""
# 插入1条
cursor.execute(insert_sql, ['monday', 0, 9999999])
# 插入多条
cursor.executemany(insert_sql, [('test', 0, 9999999), ('modely', 0, 66666666)])
update_sql = """
update sys_user2 set amount = %s where username = %s
"""
cursor.execute(update_sql, ['88888888', 'modely'])
# 注意:先查询再获取数据,不像其它语言一样直接返回结果
select_sql = """
select * from sys_user2
"""
cursor.execute(select_sql)
fetchone = cursor.fetchone()
fetchmany = cursor.fetchmany(2)
# 注意:总共有三条,上面游标已经走到最后了,所以下面游标再走就没有数据了
fetchall = cursor.fetchall()
# insert, update, delete 操作都需要显式提交
conn.commit()
# conn.rollback()
# 5.关闭游标
cursor.close()
# 关闭连接
conn.close()
以上是关于Python pymysql的主要内容,如果未能解决你的问题,请参考以下文章