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.可以做关系测试, ...
随机推荐
- 喵星之旅-狂奔的兔子-docker安装和基本使用
一.前提条件 目前,CentOS 仅发行版本中的内核支持 Docker. 位.系统内核版本为 3.10 以上. 位系统.参考喵星之旅-狂奔的兔子-linux安装 二.CentOS 7下安装 Doc ...
- 12、API - 输入设备(API - Input Devices)
学习目录:树莓派学习之路-GPIO Zero 官网地址:https://gpiozero.readthedocs.io/en/stable/api_input.html 环境:UbuntuMeta-1 ...
- 消息队列(四)--- RocketMQ-消息发送
概述 RocketMQ 发送普通消息有三种 可靠同步发送 可靠异步发送 单向(oneway)发送 :只管发送,直接返回,不等待消息服务器的结果,也不注册回调函数,简单地说,就是只管发,不管信息是否发送 ...
- H2知识小结
1.官网: http://www.h2database.com/html/main.html file:///E:/Develop/H2/docs/html/tutorial.html#web_app ...
- 点击<a href="#">阻止自动跳转到顶部方法
最近开发web项目,遇到一个问题 ,就是在<a>标签加href="#",并增加onclick事件,页面会自动在点击该标签绑定的元素时,自动跳转到页面顶部,在网上寻求了一 ...
- Python使用Tensorflow出现错误: UserWarning: The default mode, 'constant'
Python使用Tensorflow出现错误: UserWarning: The default mode, 'constant', will be changed to 'reflect' in s ...
- SQLite - C/C++接口 API(二)
1.打开数据库 SQLITE_API int sqlite3_open16( const void *filename, /* Database filename (UTF-16) */ sqlite ...
- python查看包路径及对象的所有方法名
进入python环境: python 输入如下代码: import sys sys.path = sys.path[:] import django print(django.__path__) 得到 ...
- 路由器安全-FPM
1.FPM(也叫NGACL) FPM是Cisco IOS新一代的ACL,叫做Flexible Packet Matching,灵活的包匹配. 根据任意条件,无状态的匹配数据包的头部,负载,或者全部. ...
- 实际中可能遇到的NAT问题(IPsec)
一.背景介绍:一般我们在实际网络中不是IPSec VPN的时候,都是边界设备连接Internet,然后两个边界设备通过Internet去实现互通,建立VPN,但是,有的运营商在分配IP地址的时候,给我 ...