封装成类
import pymysql
class Mysql:
def __init__(self):
self.db = pymysql.connect('localhost', 'root', 'yellow', charset='utf8', db=base_name)
self.cursor = self.db.cursor()
def __del__(self):
self.cursor.close()
self.db.close()
def commit(self, sentence, arg=None):
try:
self.cursor.execute(sentence, arg) if arg else self.cursor.execute(sentence)
self.db.commit()
except Exception as error:
print('\033[033m', error, sentence, arg, '\033[0m', sep='\n')
def fetchall(self, query):
self.cursor.execute(query)
return self.cursor.fetchall()
def fetchone(self, query):
self.cursor.execute(query)
one = self.cursor.fetchone()
while one:
yield one
one = self.cursor.fetchone()
def insert(self, dt, table):
ls = list(dt)
sentence = 'INSERT %s(' % table + ','.join(ls) + ')VALUES(' + \
','.join(['%({})r'.format(field) for field in ls]) + ');'
self.commit(sentence, dt)
def update(self, dt_update, dt_condition, table):
sentence = 'UPDATE %s SET ' % table + ','.join(['%s=%r' % (k, dt_update[k]) for k in dt_update])\
+ ' WHERE ' + ' AND '.join(['%s=%r' % (k, dt_condition[k]) for k in dt_condition]) + ';'
self.commit(sentence)
常用建表SQL
CREATE TABLE tb_name(
serial_number INT(9) PRIMARY KEY AUTO_INCREMENT COMMENT '编号',
url char(255) UNIQUE NOT NULL COMMENT '统一资源定位符',
title VARCHAR(255) COMMENT '标题',
detail TEXT COMMENT '细节',
price FLOAT(3,2) UNSIGNED DEFAULT 1.23 COMMENT '价格',
public_time DATETIME COMMENT '发布时间',
collect_date DATE COMMENT '采集日期'
);
基础补充
Python 操作 MySQL 基础
Python 任意字典生成 SQL(insert 语句)
Python 任意字典生成 SQL(update 语句)