数据库操作
创建类连接一个数据库,并定义函数实现基本的增删改查操作:
class Sql(object):
def __init__(self):
self.conn = pymysql.connect(host='', user='', password='', port='', database='', charset='',local_infile=)
# charset为编码格式,一般使用 utf-8, local_infile用于对数据库的修改,=1-允许修改,=0-不允许修改
self.cursor = self.conn.cursor()
def insert(self, table, value):
# 向数据库中插入一条新数据
insert = """insert into `%s` values (%s);""" % (table,value)
self.cursor.execute(insert)
self.conn.commit()
# 必须有self.conn.commit()这一条命令否则无法将数据插入到数据库,删改操作同理。
def delete(object, table, condition):
# 删除数据库table表中满足condition条件的数据,condition为一个字符串
delete = """delete from `%s` where %s;""" % (table, condition)
self.cursor.execute(delete)
self.conn.commit()
def update(self, table, set, condition):
# 更新数据库table表中满足condition条件的数据,将值改为set
update = """update `%s` set %s where %s;""" % (table, set, condition)
self.cursor.execute(delete)
self.conn.commit()
def select(object, table, target. condition):
# 查询数据库table表中满足condition条件的target数据
select = """ select %s from `%s` where %s;""" % (target, table, condition)
self.cursor.execute(select)
selected = list(self.cursor.fetchall())
return selected
def close(self):
self.cursor.close()
self.conn.close()
例子
如现在有一个数据表 Data
name | id | score |
---|---|---|
Frank | 001 | 99 |
Ciel | 002 | 95 |
Grey | 003 | 98 |
db = Sql()
1. 增
向数据库中插入一条(James, 004, 90)的数据
value = "'James', '004',90"
table = 'Data'
db.insert(table, value)
2.删
删除数据库中 id = 003的数据
table = 'Data'
condition = "id='003'"
db.delete(table, condition)
3. 改
修改Ciel的成绩为100
table = 'Data'
set = "score = 100"
condition = "name = 'Ciel'"
db.updata(table, set, condition)
4. 查
查询数据库中成绩高于95的id
table = 'Data'
target = 'id'
condition = "score > 95"
db.select(table, target, condition)