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.可以做关系测试, ...
随机推荐
- LR编写webservice协议接口
转自:http://lovesoo.org/use-loadrunner-call-webservice-interface-testing-optimization-summary.html 本文主 ...
- HDU-1702-ACboy needs your help again!(Stack)
队列和栈的判空都可以用empty #include <bits/stdc++.h> using namespace std; string oper,stru; int T,M,num; ...
- Windows上面搭建FlutterAndroid运行环境
1.下载安装JDK https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html 2.配置J ...
- dropna fillna
# NaN 浮点类型 np.nan+1 =>nan Python type(None) // NoneType类型 不能参与运算 import pandas as pd from pand ...
- Shiro入门学习之自定义Realm实现授权(五)
一.自定义Realm授权 前提:认证通过,查看Realm接口的继承关系结构图如下,要想通过自定义的Realm实现授权,只需继承AuthorizingRealm并重写方法即可 二.实现过程 1.新建mo ...
- 【STM32H7教程】第56章 STM32H7的DMA2D应用之刷色块,位图和Alpha混合
完整教程下载地址:http://www.armbbs.cn/forum.php?mod=viewthread&tid=86980 第56章 STM32H7的DMA2D应用之刷色块, ...
- DataGrid 獲取 制定 row Col 單元格
public static class DataGridHelper { /// <summary> /// Gets the v ...
- linux理论知识点(用于考试)
ps:为其十天左右的linux培训即将结束了,未雨绸缪,为了更好的通过之后的考试,提前多看些考试题和知识点.这是在chinaunix论坛看到的一个帖子,贴来分享. 原文地址:[http://bbs.c ...
- numpy.eye() 生成对角矩阵
numpy.eye(N,M=None, k=0, dtype=<type 'float'>) 关注第一个第三个参数就行了 第一个参数:输出方阵(行数=列数)的规模,即行数或列数 第三个参数 ...
- 23 JavaScript规范与最佳实践&性能&箭头函数
大多数web服务器(Apache等)对大小写敏感,因此命名注意大小写 不要声明字符串.数字和布尔值,始终把他们看做原始值而非对象,如果把这些声明为对象,会拖慢执行速度 对象是无法比较的,原始值可以 不 ...