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的存储的更多相关文章

  1. python中mysql数据库的操作-sqlalchemy

    MySQLdb支持python2.*,不支持3.* ,python3里面使用PyMySQL模块代替 python3里面如果有报错  django.core.exceptions.ImproperlyC ...

  2. python中mysql主从同步配置的方法

    1)安装mysql ubuntu中安装一台mysql了,docker安装另外一台mysql 获取mysql的镜像,主从同步尽量保证多台mysql的版本相同,我的ubuntu中存在的mysql是5.7. ...

  3. python中的数据存储认识

    声明:本人是一个初学者,博客内容基本也是一些基础的东西,如果说的有什么问题欢迎纠正. 前言 许多人初学python之前应该也学习过其他的语言,比如博大精深的c语言,笔者在学习python之前就学习过c ...

  4. sae python中Mysql中文乱码的解决

    一開始我用的是: db=MySQLdb.connect(db=sae.const.MYSQL_DB,user=sae.const.MYSQL_USER,passwd=sae.const.MYSQL_P ...

  5. Python 中 mySQL 中的语句

    class DeleteInventorybusiness(BaseBusiness): def DeleteInventory(self,Delete_goodsID): DeleteInvento ...

  6. 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 ...

  7. 如何在python中读写和存储matlab的数据文件(*.mat)

    使用sicpy.io即可.sicpy.io提供了两个函数loadmat和savemat,非常方便. 以前也有一些开源的库(pymat和pymat2等)来做这个事, 不过自从有了numpy和scipy以 ...

  8. python 中mysql数据库的读写

    1.读取数据库 import pymysql id=[] name=[] explain=[] db=pymysql.Connection(host=,user="root", p ...

  9. Python中MySQL插入数据

    sql = 'INSERT INTO course(class_name, credit, properties, teacher_name, college_given, classroom) ' ...

随机推荐

  1. 《GB/T 20988-2007:信息系统灾难恢复规范》[中](国家质检总局 & 国标委)阅读笔记

    第 0 章:引言 [感]GB/T 20988 引用了 SHARE 78 会议(标准)上的有关内容和思想,并结合国家重要信息系统行业技术发展和实践经验制定而成. GB/T 20988 提出了信息系统灾难 ...

  2. Mybatis多表查询(一对一、一对多、多对多)

    Mybatis的多表级联查询 . 一对一可以通过<association>实现,一对多和多对多通过<collection>实现. <discriminator> 元 ...

  3. Orientation of phone Image

    相机拍摄的图像方向问题 Description 很多时候,我们习惯把手机相机拍摄的图像在电脑上面查看.有的时候在手机上面看图像是正的,可是电脑端查看是反的:有的时候手机和电脑都是反的:有的时候都是正的 ...

  4. Js And PHP Modify Cookie

    简单的js函数封装cookie //设置cookie function setCookie(cname, cvalue, exdays) { var d = new Date(); d.setTime ...

  5. Qt的安装和使用中的常见问题(简略版)

    对于喜欢研究细节的朋友,可参考Qt的安装和使用中的常见问题(详细版). 目录 1.引入 2.Qt简介 3.Qt版本 3.1 查看安装的Qt版本 3.2 查看当前项目使用的Qt版本 3.3 查看当前项目 ...

  6. C++中static修饰的静态成员函数、静态数据成员

    1.静态成员函数.静态数据成员 在类中,用static修饰的成员函数被称为静态成员函数,而用static修饰的数据成员就称为静态数据成员:与普通的成员函数和数据成员不同, 静态成员函数和静态数据成员有 ...

  7. postman的使用方法详解!最全面的教程

      文章来源:http://www.cnplugins.com/tool/specify-postman-methods.html     一 简介 Postman 是一款功能超级强大的用于发送 HT ...

  8. polymer-developer guide-feature overview

    <dom-module id='proto-element'> <template> <div>{{greeting}}</div> </temp ...

  9. 寻找最大的K个数(上)

    这是一道很经典的题目,有太多方法了,今天写了两种方法,分别是快排和堆排序 #include <iostream> using namespace std; #define N 25 //初 ...

  10. 搭建一个基于CentOS的可视化zookeeper管理工具zkUI实现对zk的可视化管理

    一. zookeeper 可视化工具   JMX => CLRProfile ZKUI => java写的一个可视化的web网站 github中下载 https://github.com/ ...