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) ' ...
随机推荐
- 判断viewpager左右滑动方向
实现思路就是通过viewpager的滑动监听,用参数position进行比较,同时当判断完这个要把比较的positon覆盖.这里简单介绍一下public void onPageScrolled(int ...
- 02-SSH综合案例:需求分析(后台)
1.1.7 用户模块:(后台) 不用添加了,添加的话在前台就注册了. 查询所有用户: 修改用户信息: 删除用户信息: 1.1.8 一级分类:(后台) 主要都还是增删改查的操作 查询所有一级分类: ...
- vnc安装
安装命令:yum install tigervnc-server 一.启动VNC服务 输入命令 vncserver ps -ef|grep Xvnc vncserver -geometry 800x6 ...
- 用 AutoHotKey 随时记录所想
别被标题咋呼了,其实很简单,按下快捷键自动打开指定文本文档,自动加上当前时间日期,适合像我这种无聊的人记录生活. ;Alt+X 调出 !X:: ;获取当前日期时间并保存到剪贴板 d = @rhinoc ...
- Solidity根据精度来表示浮点数
https://stackoverflow.com/questions/42738640/division-in-ethereum-solidity/42739843 pragma solidity ...
- Linux gperf命令
一.简介 GNU 的 gperf 工具是一种 "完美的" 散列函数,可以为用户提供的一组特定字符串生成散列表.散列函数和查找函数的 C/C++ 代码.通过本文学习如何使用 gper ...
- [Training Video - 5] [Groovy Script Test Step - Collections, Exceptions] Array and ArrayList
Array: def x = new String[5] x[0] = "India" x[1] = "USA" x[2] = "Korea" ...
- SLAM拾萃(1):octomap
前言 大家好,时隔多年之后,我又开始了博客旅程.经历了很多事情之后呢,我发现自己的想法真的很简单:好好读书做课题,闲下来时写写博客,服务大家.所以我会继续写SLAM相关的博客.如果你觉得它对你有帮助, ...
- mongon命令(转)
原文:http://www.cnblogs.com/blueness-sunshine/p/6139092.html 连接mongodb: mongo -u --authenticationDat ...
- WebStorm + JetBrains IDE Support 实现自动刷新功能
WebStorm 7.0 + live eidt + JetBrains IDE Support 实现自动刷新功能, WebStorm 7.0 已自带live eidt扩展 并可更改端口,WebSto ...