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包操作数据库的更多相关文章

  1. python学习笔记(九):操作数据库

    我们在写代码的时候,经常会操作数据库,增删改查,数据库有很多类型,关系型数据库和非关系数据库,这里咱们介绍一下python怎么操作mysql.redis和mongodb. 一.python操作mysq ...

  2. Python学习系列(五)(文件操作及其字典)

    Python学习系列(五)(文件操作及其字典) Python学习系列(四)(列表及其函数) 一.文件操作 1,读文件      在以'r'读模式打开文件以后可以调用read函数一次性将文件内容全部读出 ...

  3. python学习9—文件基本操作与高级操作

    python学习9—文件基本操作与高级操作 1. 文件基本操作 打开文件,获得文件句柄:f = open('filename',encoding='utf-8'),open会查询操作系统的编码方式,并 ...

  4. Python3.x使用PyMysql连接MySQL数据库

    Python3.x使用PyMysql连接MySQL数据库 由于Python3.x不向前兼容,导致Python2.x中的很多库在Python3.x中无法使用,例如Mysqldb,我前几天写了一篇博客Py ...

  5. 第二百七十九节,MySQL数据库-pymysql模块操作数据库

    MySQL数据库-pymysql模块操作数据库 pymysql模块是python操作数据库的一个模块 connect()创建数据库链接,参数是连接数据库需要的连接参数使用方式: 模块名称.connec ...

  6. 基于Python的接口自动化实战-基础篇之pymysql模块操作数据库

    引言 在进行功能或者接口测试时常常需要通过连接数据库,操作和查看相关的数据表数据,用于构建测试数据.核对功能.验证数据一致性,接口的数据库操作是否正确等.因此,在进行接口自动化测试时,我们一样绕不开接 ...

  7. 人脸检测? 对Python来说太简单, 调用dlib包就可以完成

    "Dlib 是一个现代化的 C ++ 工具包,包含用于创建复杂软件的机器学习算法和工具 " .它使您能够直接在 Python 中运行许多任务,其中一个例子就是人脸检测. 安装 dl ...

  8. Python学习(六)模块 —— 包

    Python 包 包 定义 为了组织好模块,会将多个模块分为包.Python 处理包也是相当方便的.简单来说,包就是文件夹,但该文件夹下必须存在 __init__.py 文件. 常见的包结构如下:

  9. python学习笔记(二)文件操作和集合

    集合: 集合也是一种数据类型,一个类似列表东西,它的特点是无序的,不重复的,也就是说集合中是没有重复的数据 集合的作用: 1.它可以把一个列表中重复的数据去掉,而不需要你再写判断 2.可以做关系测试, ...

随机推荐

  1. 最大m段子段和 Day9 - E - Max Sum Plus Plus HDU - 1024

    Now I think you have got an AC in Ignatius.L's "Max Sum" problem. To be a brave ACMer, we ...

  2. ZOJ1002 —— 深度优先搜索

    ZOJ1002 —— Fire net Time Limit: 2000 ms Memory Limit: 65536 KB Suppose that we have a square city wi ...

  3. 《爬虫学习》(三)(requests库使用)

    requests库 虽然Python的标准库中 urllib模块已经包含了平常我们使用的大多数功能,但是它的 API 使用起来让人感觉不太好,而 Requests宣传是 “HTTP for Human ...

  4. 03-Spring的IOC示例程序(通过类型获取对象)

    根据bean类型从IOC容器中获取bean的实例 ①test测试类 @Test public void Test02() { //获取spring容器对象 ApplicationContext app ...

  5. 什么是buffer?

    Buffer 类的实例类似于整数数组,但 Buffer 的大小是固定的.且在 V8 堆外分配物理内存. Buffer 的大小在被创建时确定,且无法调整. Buffer 类在 Node.js 中是一个全 ...

  6. FULL OUTER JOIN

    FULL OUTER JOIN 关键字只要左表(table1)和右表(table2)其中一个表中存在匹配,则返回行. SELECT Web.name, access.count, access.dat ...

  7. lucky 的 时光助理(3)

    今天lucky小姐哭笑不得的说, 昨天下班时跟经理一起走的时候, 地铁站手机被小偷偷走,那时一个人孤单单的,除了惊愕, 她不知道该去联系谁, 借了同事的手机,给家里打去电话. 她说,因为那是她唯一记得 ...

  8. python3中的raise使用

    raise表示会抛出异常那么就是说raise会向python的解释器一个响应告诉解释器他的后面是一个异常让我们的程序中断 一般是和自定义的异常连用. class CustomError(Excepti ...

  9. accordion(折叠面板)的使用

    一.前言: 折叠面板(accordion)允许使用多面板(panel),同时显示一个或多个面板(panel).每个面板(panel)都有展开和折叠的内建支持.点击面板(panel)头部可展开或折叠面板 ...

  10. MDC 输出线程信息帮助定位问题

    log4j中的%x ---NDC,%X---MDC 即%x NDC.clear();NDC.push(this.toString());%X{first} %X{last}MDC.put(" ...