pymysql保存数组_pymysql库的学习

本文介绍了如何使用pymysql库操作MySQL数据库,包括连接数据库、创建表、插入、更新、删除数据,以及处理日期对象。强调了在执行SQL时避免直接包含实际值,建议使用参数化查询,并提供了日期对象与字符串相互转换的方法。
摘要由CSDN通过智能技术生成

pymysql基础学习

mysql返回对象和python对象的转换

元组转换为列表

datetime.date对象和字符串的转换

游标和事务管理

游标协调mysql的集合处理方式和python的一行一行处理

事务管理还要懂得sql呀——

pymysql只是一个对接mysql的库,sql语句才是精髓,在使用pymysql的库中,对execute(sql,arg)中的sql语句尽量不包括实际值,用arg替代

库中Date类的时间函数

ctime

day

fromisocalendar

fromisoformat

fromordinal

fromtimestamp

isocalendar

isoformat

isoweekday

max

min

month

replace

resolution

strftime

timetuple

today

toordinal

weekday

year

字符串和datetime.date对象的转换

isoformat() 2000-07-03

isocalendar() (2000, 27, 1) tuple对象

isoweekday() 1-7 int 周一到周日

weekday() 0-6

详细讲解https://www.runoob.com/python/att-time-strftime.html

for date in result:

str=date.strftime('%Y-%m-%d')#位置可以自由组合,个数也可以自由组合

#只可以转换标准的YY-MM-DD

date=Date.fromisoformat(date) #class method

#自由组合例子

# date=date.strftime('%b %d %Y')

import pymysql

#连接数据库

db = pymysql.connect(host='localhost',user='root', password='11111111', port=3306)

cursor = db.cursor()

#创建表,只需执行一次

cursor.execute('use spiders')

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)

#插入

data = {

'id': '20120001',

'name': 'Bob',

'age': 20

}

table = 'students'

keys = ', '.join(data.keys())

values = ', '.join(['%s'] * len(data))

sql = 'INSERT INTO {table}({keys}) VALUES ({values})'.format(table=table, keys=keys, values=values)

try:

if cursor.execute(sql, tuple(data.values())):

print('Successful')

db.commit()

except:

print('Failed')

db.rollback()#事务回滚

#更新数据

sql = 'UPDATE students SET age = %s WHERE name = %s'

try:

cursor.execute(sql, (25, 'Bob'))

db.commit()

except:

db.rollback()

#如果插入值重复就不插入

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()

#删除操作

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()

#查询数据要注意,数据量过大要迭代返回

sql = 'SELECT * FROM students WHERE age >= 20'

try:

cursor.execute(sql)

print('Count:', cursor.rowcount)

row = cursor.fetchone() #fetchmany(size)

while row:

print('Row:', row)

row = cursor.fetchone()

except:

print('Error')

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值