Python爬虫学习笔记(Mysql 存储)

1.连接数据库

import pymysql

db = pymysql.connect(host='localhost',user='root',password='******',port=3306) #声明MySQL连接对象db
cursor = db.cursor() #获得MySQL的操作游标,利用游标执行SQL 语句
cursor.execute('SELECT VERSION()')  #执行SQL语句,获得当前版本
data = cursor.fetchone() #获得版本的第一条数据
print('Database version:',data)
cursor.execute("CREATE DATABASE spiders DEFAULT CHARACTER SET utf8") #执行SQL语句,创建数据库
db.close()

 

2.创建数据表

import pymysql

# spiders数据库中创建students数据表
db = pymysql.connect(host='localhost',user='root',password='******',port=3306,db='spiders') #声明MySQL连接对象db
cursor = db.cursor() #获得MySQL的操作游标,利用游标执行SQL 语句
sql = 'CREATE TABLE  IF NOT EXISTS student(id VARCHAR(255) NOT NULL,name VARCHAR(255) NOT NULL,age INT NOT NULL,PRIMARY KEY(id))'#创建数据表student
cursor.execute(sql)
db.close()

 

3.向数据表插入数据

import pymysql

# spiders数据库中student数据表写入数据
data={
    'id':'001',
    'name':'Bob',
    'age': 20
}
db = pymysql.connect(host='localhost',user='root',password='******',port=3306,db='spiders') #声明MySQL连接对象db
cursor = db.cursor() #获得MySQL的操作游标,利用游标执行SQL 语句
table = 'student'
keys=', '.join(data.keys()) #写入键
values = ', '.join(['%s'] * len(data)) #定义占位符数组
sql = 'INSERT INTO {table}({keys}) VALUES ({values})'.format(table=table,keys=keys,values=values)
#sql = 'INSERT INTO student(id,name,age) values (%s,%s,%s)'#格式化写入数据
try:
    if cursor.execute(sql,tuple(data.values())):
        print('Successful')
        db.commit()
except:
    print('Failed')
    db.rollback()
db.close()

 

 

4.更新数据

import pymysql

# spiders数据库中student数据表写入数据
data={
    'id':'001',
    'name':'Bob',
    'age': 21
}
db = pymysql.connect(host='localhost',user='root',password='*******',port=3306,db='spiders') #声明MySQL连接对象db
cursor = db.cursor() #获得MySQL的操作游标,利用游标执行SQL 语句
table = 'student'
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
#sql = 'INSERT INTO student(id,name,age) values (%s,%s,%s)'#格式化写入数据
try:
    if cursor.execute(sql,tuple(data.values())*2):
        print('Successful')
        db.commit()
except:
    print('Failed')
    db.rollback()
db.close()

 

5.删除数据

import pymysql
db = pymysql.connect(host='localhost',user='root',password='******',port=3306,db='spiders') #声明MySQL连接对象db
cursor = db.cursor() #获得MySQL的操作游标,利用游标执行SQL 语句
table = 'student'
condition = 'age>20'
sql = 'DELETE FROM {table} WHERE {condition}'.format(table=table,condition=condition)
try:
    if cursor.execute(sql):
        db.commit()
except:
    print('Failed')
    db.rollback()
db.close()

 

 

6.查找数据

import pymysql

db = pymysql.connect(host='localhost',user='root',password='*******',port=3306,db='spiders') #声明MySQL连接对象db
cursor = db.cursor() #获得MySQL的操作游标,利用游标执行SQL 语句
table = 'student'
condition='age>20'
sql = 'SELECT * FROM {table} WHERE {condition}'.format(table=table,condition=condition)
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) #打印从当前指针位置,即第二条往后的所有符合条件的数据
    #db.commit()
except:
    print('Failed')
    db.rollback()
db.close()

 

也可以使用while循环打印所有符合条件的数据

import pymysql

db = pymysql.connect(host='localhost',user='root',password='*****',port=3306,db='spiders') #声明MySQL连接对象db
cursor = db.cursor() #获得MySQL的操作游标,利用游标执行SQL 语句
table = 'student'
condition='age>20'
sql = 'SELECT * FROM {table} WHERE {condition}'.format(table=table,condition=condition)
try:
    cursor.execute(sql)
    print('Count:',cursor.rowcount) #符合条件的数据数
    row = cursor.fetchone()
    while row:
        print('Row:',row)
        row = cursor.fetchone()
    #db.commit()
except:
    print('Failed')
    db.rollback()
db.close()

 
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值