python中mysql的存储
1. 连接mysql
import pymysql db = pymysql.connect(host='localhost', user='root', password='', port=3306)
cursor = db.cursor() cursor.execute('select version()')
data = cursor.fetchone()
print('database version:', data)
cursor.execute('create database spider default character set utf8')
db.close()
2. 创建表
import pymysql db = pymysql.connect(host='localhost', user='root', password='', port=3306, db='spider')
cursor = db.cursor() sql = 'create table if not exists students (id varchar(255) not null, name varchar(255) not null, age int not null, PRIMARY KEY (id))'
cursor.execute(sql)
db.close()
3. 插入数据
mport pymysql
id = ''
user = 'bob'
age = 20 db=pymysql.connect(host='localhost', user='root', password='', port=3306, db='spider')
cursor = db.cursor() sql = 'insert into students(id,name,age) values(%s, %s, %s)'
try:
cursor.execute(sql, (id, user, age))
db.commit()
except:
db.rollback()
db.close()
4. 更新数据
4.1:普通更新
import pymysql
db=pymysql.connect(host='localhost', user='root', password='', port=3306, db='spider')
cursor= db.cursor() sql = "update spider.students set age = %s where name = %s"
try:
cursor.execute(sql, (20, 'bob'))
db.commit()
except:
db.rollback()
db.close()
4.2:去重更新
如果主键存在就更新,不存在就新增
import pymysql db=pymysql.connect(host='localhost', user='root', password='', port=3306, db='spider')
cursor= db.cursor() data = {
'id':'',
'name': 'jack',
'age': 21
} table = 'students'
keys = ', '.join(data.keys())
values = ', '.join(['%s'] * len(data)) sql = 'insert into {table}({keys}) values ({values}) on duplicate key update'.format(table=table, keys=keys, values=values)
update = ','.join([" {key} = %s".format(key=key) for key in data])
sql += update
try:
if cursor.execute(sql, tuple(data.values())*2):
print('Successful')
db.commit()
except:
print('Failed')
db.rollback()
db.close()
分析理解
>>> keys = ', '.join(data.keys())
>>> keys
'age, name, id' >>> values = ', '.join(['%s'] * len(data))
>>> values
'%s, %s, %s' >>> table = 'students'
>>> sql = 'insert into {table}({keys}) values ({values}) on duplicate key update'.format(table=table, keys=keys, values=values)
>>> sql
'insert into students(age, name, id) values (%s, %s, %s) on duplicate key update' >>> update = ','.join([" {key} = %s".format(key=key) for key in data])
>>> update
' age = %s, name = %s, id = %s' >>> sql+=update
>>> sql
'insert into students(age, name, id) values (%s, %s, %s) on duplicate key update age = %s, name = %s, id = %s' >>> data.values()
dict_values([, 'jack', ''])
>>> tuple(data.values())
(, 'jack', '') >>> tuple(data.values())*
(, 'jack', '', , 'jack', '')
5. 删除数据
import pymysql
db=pymysql.connect(host='localhost', user='root', password='', port=3306, db='spider')
cursor= db.cursor() table = 'students'
condition = 'age > 20'
sql= 'delete from {table} where {condition}'.format(table=table, condition=condition) try:
cursor.execute(sql)
db.commit()
except:
db.rollback() db.close()
6. 查询数据
import pymysql
db=pymysql.connect(host='localhost', user='root', password='', port=3306, db='spider')
cursor= db.cursor() sql = 'select * from students where age >= 20' try:
cursor.execute(sql)
print('Count:', cursor.rowcount) # 有几条符合条件的数据 one = cursor.fetchone() # 取出第一条数据
print('One:', one) results = cursor.fetchall() # 取出剩下的所有数据,上面的第一条不会提取
print('Results:',results)
print('Results Type:', type(results)) # 类型是元组
for row in results:
print(row) except:
print('Error')
python中mysql的存储的更多相关文章
- python中mysql数据库的操作-sqlalchemy
MySQLdb支持python2.*,不支持3.* ,python3里面使用PyMySQL模块代替 python3里面如果有报错 django.core.exceptions.ImproperlyC ...
- python中mysql主从同步配置的方法
1)安装mysql ubuntu中安装一台mysql了,docker安装另外一台mysql 获取mysql的镜像,主从同步尽量保证多台mysql的版本相同,我的ubuntu中存在的mysql是5.7. ...
- python中的数据存储认识
声明:本人是一个初学者,博客内容基本也是一些基础的东西,如果说的有什么问题欢迎纠正. 前言 许多人初学python之前应该也学习过其他的语言,比如博大精深的c语言,笔者在学习python之前就学习过c ...
- sae python中Mysql中文乱码的解决
一開始我用的是: db=MySQLdb.connect(db=sae.const.MYSQL_DB,user=sae.const.MYSQL_USER,passwd=sae.const.MYSQL_P ...
- Python 中 mySQL 中的语句
class DeleteInventorybusiness(BaseBusiness): def DeleteInventory(self,Delete_goodsID): DeleteInvento ...
- python中MySQL模块TypeError: %d format: a number is required, not str异常解决
转载自:http://www.codeif.com/topic/896 python代码: attr_sql = "INSERT INTO `ym_attribute` (`attr_nam ...
- 如何在python中读写和存储matlab的数据文件(*.mat)
使用sicpy.io即可.sicpy.io提供了两个函数loadmat和savemat,非常方便. 以前也有一些开源的库(pymat和pymat2等)来做这个事, 不过自从有了numpy和scipy以 ...
- python 中mysql数据库的读写
1.读取数据库 import pymysql id=[] name=[] explain=[] db=pymysql.Connection(host=,user="root", p ...
- Python中MySQL插入数据
sql = 'INSERT INTO course(class_name, credit, properties, teacher_name, college_given, classroom) ' ...
随机推荐
- Redis 字典的实现
[Redis 字典的实现] 注意 dict 类型使用了两个指针,分别指向两个哈希表. 其中, 0 号哈希表(ht[0])是字典主要使用的哈希表, 而 1 号哈希表(ht[1])则只有在程序对 0 号哈 ...
- css中的display(显示)和visibility(可见性)
display定义和用法 display 属性规定元素应该生成的框的类型. 说明 这个属性用于定义建立布局时元素生成的显示框类型.对于 HTML 等文档类型,如果使用 display 不谨慎会很危险, ...
- shell脚本学习指南-grep文本搜索命令-学习(3)
1.作用 Linux系统中grep命令是一种强大的文本搜索工具,它能使用正则表达式搜索文本,并把匹 配的行打印出来.grep全称是Global Regular Expression Print,表示全 ...
- Django模板层
一:模板简介 二:模板语法值变量 三: 模板之过滤器 四: 模板之标签 五:自定义标签和过滤器 一:模板简介 def current_datetime(request): now=datetime ...
- mysql查询今天、昨天、近7天、近30天、本月、上一月的SQL语句
mysql查询今天.昨天.近7天.近30天.本月.上一月的SQL语句 这篇文章主要介绍了mysql查询今天.昨天.近7天.近30天.本月.上一月的SQL语句,一般在一些统计报表中比较常用这个时间段,需 ...
- 用Word2007写CSDN博客
目前大部分的博客作者在用Word写博客这件事情上都会遇到以下3个痛点: 1.所有博客平台关闭了文档发布接口,用户无法使用Word,Windows Live Writer等工具来发布博客.使用Word写 ...
- .NET基础 (19)多线程
多线程编程的基本概念1 请解释操作系统层面上的线程和进程2 多线程程序在操作系统里是并行执行的吗3 什么是纤程 .NET中的多线程1 如何在.NET程序中手动控制多个线程2 如何使用.NET的线程池3 ...
- Android如何判断当前手机是否正在播放音乐,并获取到正在播放的音乐的信息
我想实现如下的场景,判断当前Android手机上是否正在播放音乐,如果是,通过某个特定的手势, 或者点击某个按键,将当前我正在听的音乐共享出去. 第一步,就是判断当前是否有音乐正在播放. 最开始我想得 ...
- 23 DesignPatterns学习笔记:C++语言实现 --- 2.2 Adapter
23 DesignPatterns学习笔记:C++语言实现 --- 2.2 Adapter 2016-07-22 (www.cnblogs.com/icmzn) 模式理解
- D3.js的基础部分之数组的处理 映射(v3版本)
映射(Map) 映射(Map)是十分常见的一种数据结构,由一系列键(key)和值(value)组成的.每个key对应一个value,根据key可以获取和设定value,也可以根据key来查询val ...