python学习 —— python3简单使用pymysql包操作数据库
python3只支持pymysql(cpython >= 2.6 or >= 3.3,mysql >= 4.1),python2支持mysqldb。
两个例子:
import pymysql
db = pymysql.connect('localhost', 'root', '123456', 'crawlsql')
cursor = db.cursor()
try:
create_table_sql = "CREATE TABLE IF NOT EXISTS `table` (" \
"`id` int(11) NOT NULL AUTO_INCREMENT," \
"`url` varchar(255) NOT NULL," \
"`path` varchar(255) NOT NULL," \
"`size` float NOT NULL," \
"PRIMARY KEY(`id`)" \
") ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;"
cursor.execute(create_table_sql)
db.commit()
show_table_sql = "SELECT `table` FROM information_schema.tables WHERE table_schema = `crawlsql`;"
cursor.execute(show_table_sql)
result = cursor.fetchone()
print(result)
finally:
db.close()
注意在创建名加上`而不是'(我经历的一个小坑)。
这个例子实现了连接mysql中的crawlsql数据库以及创建张名为'table'的表。查看crawlsql数据库下的table表语句(第17行)报错误:
pymysql.err.InternalError: (1054, "Unknown column 'table' in 'field list'")
官方例子(稍微做了一点修改以满足官方结果):
import pymysql.cursors # Connect to the database
connection = pymysql.connect(host='localhost',
user='root',
password='123456',
db='crawlsql',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor) try:
with connection.cursor() as cursor:
sql = "CREATE TABLE IF NOT EXISTS `table` (" \
"`id` int(11) NOT NULL AUTO_INCREMENT," \
"`email` varchar(50) NOT NULL," \
"`password` varchar(30) NOT NULL," \
"PRIMARY KEY(`id`)" \
") ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1"
cursor.execute(sql) connection.commit() with connection.cursor() as cursor:
# Create a new record
sql = "INSERT INTO `table` (`email`, `password`) VALUES (%s, %s)"
cursor.execute(sql, ('webmaster@python.org', 'very-secret')) connection.commit() with connection.cursor() as cursor:
# Read a single record
sql = "SELECT `id`, `password` FROM `table` WHERE `email`=%s"
cursor.execute(sql, ('webmaster@python.org',))
result = cursor.fetchone()
print(result)
finally:
connection.close()
运行结果:
{'id': 1, 'password': 'very-secret'}
Process finished with exit code 0
再修改一点点(没有意义):
import pymysql.cursors # Connect to the database
connection = pymysql.connect(host='localhost',
user='root',
password='123456',
db='crawlsql',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor) try:
with connection.cursor() as cursor:
sql = "CREATE TABLE IF NOT EXISTS `table` (" \
"`id` int(11) NOT NULL AUTO_INCREMENT," \
"`email` varchar(50) NOT NULL," \
"`password` varchar(30) NOT NULL," \
"PRIMARY KEY(`id`)" \
") ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1"
cursor.execute(sql) connection.commit() with connection.cursor() as cursor:
# Create a new record
sql = "INSERT INTO `table` (`email`, `password`) VALUES (%s, %s)"
cursor.execute(sql, ('webmaster@python.org', 'very-secret')) connection.commit() with connection.cursor() as cursor:
# Read a single record
sql = "SELECT * FROM `table`"
cursor.execute(sql)
result = cursor.fetchone()
print(result)
finally:
connection.close()
运行结果:
{'id': 1, 'email': 'webmaster@python.org', 'password': 'very-secret'}
Process finished with exit code 0
python学习 —— python3简单使用pymysql包操作数据库的更多相关文章
- python学习笔记(九):操作数据库
我们在写代码的时候,经常会操作数据库,增删改查,数据库有很多类型,关系型数据库和非关系数据库,这里咱们介绍一下python怎么操作mysql.redis和mongodb. 一.python操作mysq ...
- Python学习系列(五)(文件操作及其字典)
Python学习系列(五)(文件操作及其字典) Python学习系列(四)(列表及其函数) 一.文件操作 1,读文件 在以'r'读模式打开文件以后可以调用read函数一次性将文件内容全部读出 ...
- python学习9—文件基本操作与高级操作
python学习9—文件基本操作与高级操作 1. 文件基本操作 打开文件,获得文件句柄:f = open('filename',encoding='utf-8'),open会查询操作系统的编码方式,并 ...
- Python3.x使用PyMysql连接MySQL数据库
Python3.x使用PyMysql连接MySQL数据库 由于Python3.x不向前兼容,导致Python2.x中的很多库在Python3.x中无法使用,例如Mysqldb,我前几天写了一篇博客Py ...
- 第二百七十九节,MySQL数据库-pymysql模块操作数据库
MySQL数据库-pymysql模块操作数据库 pymysql模块是python操作数据库的一个模块 connect()创建数据库链接,参数是连接数据库需要的连接参数使用方式: 模块名称.connec ...
- 基于Python的接口自动化实战-基础篇之pymysql模块操作数据库
引言 在进行功能或者接口测试时常常需要通过连接数据库,操作和查看相关的数据表数据,用于构建测试数据.核对功能.验证数据一致性,接口的数据库操作是否正确等.因此,在进行接口自动化测试时,我们一样绕不开接 ...
- 人脸检测? 对Python来说太简单, 调用dlib包就可以完成
"Dlib 是一个现代化的 C ++ 工具包,包含用于创建复杂软件的机器学习算法和工具 " .它使您能够直接在 Python 中运行许多任务,其中一个例子就是人脸检测. 安装 dl ...
- Python学习(六)模块 —— 包
Python 包 包 定义 为了组织好模块,会将多个模块分为包.Python 处理包也是相当方便的.简单来说,包就是文件夹,但该文件夹下必须存在 __init__.py 文件. 常见的包结构如下:
- python学习笔记(二)文件操作和集合
集合: 集合也是一种数据类型,一个类似列表东西,它的特点是无序的,不重复的,也就是说集合中是没有重复的数据 集合的作用: 1.它可以把一个列表中重复的数据去掉,而不需要你再写判断 2.可以做关系测试, ...
随机推荐
- jquery 根据值 设置radio选中
$("[name='selector'][value='value']").prop("checked", "checked");
- win10无法登陆SSG进行WEB UI管理
故障描述:尝试登录SSG设备时,无法无法刷出页面,但是设备时可以ping通的(内部接口),可以Telnet上设备,就是无法通过网页登录. 深入测试:win7的系统可以登录,win10的不行,浏览器报协 ...
- 基于Amoeba读写分离
Amoeba 原理:amoeba相当于业务员,处理client的读写请求,并将读写请求分开处理.amoeba和master以及slave都有联系,如果是读的请求,amoeba就从slave读取信息反馈 ...
- html5的canvas2
http://www.cnblogs.com/liugang-vip/p/5360283.html http://www.cnblogs.com/liugang-vip/p/5364292.html ...
- UIViewController的API
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil; 返回一个新初始化 ...
- Springboot学习:介绍与HelloWorld
1. 什么是 Spring boot Spring Boot来简化Spring应用开发,约定大于配置,去繁从简,just run就能创建一个独立的,产品级别的应用 整个Spring技术栈的一个大整合 ...
- C#多个泛型约束问题
多个约束之间使用逗号隔开,但不重复T约束. 1. private void AddControl<T>(TabPage tabPage, T userControl) where T: U ...
- 吴裕雄 Bootstrap 前端框架开发——Bootstrap 网格系统实例:响应式的列重置
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...
- Python学习第二十一课——Mysql 对数据库的基本操作
数据库操作(DDL) 在数据库下创建表(create_table) 创建表代码块: CREATE TABLE employee( id TINYINT PRIMARY KEY auto_increme ...
- codeforces- Shortest path of the king
The king is left alone on the chessboard. In spite of this loneliness, he doesn't lose heart, becaus ...