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) ' ...
随机推荐
- Python全栈工程师(Python3 所有基础内容 0-0)
ParisGabriel 每天坚持手写 一天一篇 决定坚持几年 为了梦想为了信仰 开局一张图 Python一个月的基础语法 基本就到这咯 接下来是数据 ...
- ajax406错误
如上,ajax请求时一直返回error,但是后台已经正确返回.网上给出的解决办法是spring3.*的,但我的是sppring 4.*的,应该不适用,我也没试. 思索一下,406 not accept ...
- md5,原理待续
以前项目中copy出来的 import java.security.MessageDigest; public class MD5Util { /** * @todo MD5加码 生成32位md5码 ...
- ROS标定IDS相机
参考 ROS 相机标定http://blog.csdn.net/ArtistA/article/details/51125560 ROS里的标定程序只要使用了OPNCV的标定程序: opencv 相机 ...
- c++ template 判断是否为类类型
/* The following code example is taken from the book * "C++ Templates - The Complete Guide" ...
- 1 web应用-http协议-web框架
web 应用 Web 应用程序是一种可以通过 Web 访问的应用程序,程序的最大好处是用户很容易访问应用程序,用户只需要有浏览器即可,不需要再安装其他软件.应用程序有两种模式 C/S.B/S.C/S ...
- Hdu1560 DNA sequence(IDA*) 2017-01-20 18:53 50人阅读 评论(0) 收藏
DNA sequence Time Limit : 15000/5000ms (Java/Other) Memory Limit : 32768/32768K (Java/Other) Total ...
- B-spline Curves 学习之B样条曲线的系数计算与B样条曲线特例(6)
B-spline Curves: Computing the Coefficients 本博客转自前人的博客的翻译版本,前几章节是原来博主的翻译内容,但是后续章节博主不在提供翻译,后续章节我在完成相关 ...
- 四则运算生成器(java) 蔡苑菲,陆海燕
github地址:https://github.com/Nancy0611/Myapp.git 一.项目相关要求 使用 -n 参数控制生成题目的个数,例如 Myapp.exe -n 10 将生成10个 ...
- iOS设备抓包终极解决方案(支持https)
http://bbs.chinapyg.com/forum.php?mod=viewthread&tid=74423&extra=page%3D1%26filter%3Dtypeid% ...