查询
sql = "select * from users where username=%s and password=%s"
cursor.execute(sql,user,pwd)
插入
sql = "INSERT INTO USER(NAME,PASSWORD) VALUES(%s,%s)"
cur.execute(sql, ('test', '888888'))
更新
cs1.execute('update student set name="%s" where name ="%s"',["lv","da"])
删除
cs1.execute('delete from student where name =%s', ["haha"])
封装
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File : mysql_handle.py
# 还需要再修改,没有考虑id=2 or id =3这种情况
import pymysql
import database
class MysqlHandle(object):
def __init__(self, source, which_db):
try:
self.conn = pymysql.Connect(
host=database.CONNECTIONS[source]['HOST'],
port=database.CONNECTIONS[source]['PORT'],
db=database.CONNECTIONS[source]['DB'][which_db],
user=database.CONNECTIONS[source]['USER'],
passwd=database.CONNECTIONS[source]['PASSWD'],
charset=database.CONNECTIONS[source]['CHARSET'],
)
self.cur = self.conn.cursor()
except Exception as e:
print(e)
def select_handle(self, table_name, *query_values, **conditions): # 知识点
row = ""
if query_values == ():
row = "* "
else:
for query_value in query_values:
row += query_value + ','
try:
if conditions == {}:
sql = "select " + row[:-1] + " from " + table_name
self.cur.execute(sql)
result = self.cur.fetchall()
else:
columns = ""
values = []
for key in conditions:
columns += key + "= %s and "
values.append(conditions[key])
sql = "select " + row[:-1] + " from " + table_name + " where " + columns[:-4]
self.cur.execute(sql, values)
result = self.cur.fetchone()
# 提交事务
self.conn.commit()
except:
result = None
return result
def insert_handle(self, table_name, data):
if isinstance(data, dict):
columns = ""
values = []
variable = ""
for key in data:
columns += key + ","
values.append(data[key])
variable += "%s,"
sql = 'INSERT INTO ' + table_name + '(' + columns[:-1] + ') ' + 'VALUES' + '(' + variable[:-1] + ')'
try:
self.cur.execute(sql, values)
self.conn.commit()
except:
print("插入数据失败")
return
else:
print('不是字典')
def update_handle(self, table_name, data, **conditions):
# update student set name="haha",age="14" where name ="hehe"
if isinstance(data, dict):
data_variable = ""
data_values = []
for key in data:
data_variable += key + '="%s",'
data_values.append(data[key])
try:
if conditions == {}:
sql = "update " + table_name + " set " + data_variable[:-1]
self.cur.execute(sql, data_values)
else:
conditions_variable = ""
conditions_values = []
for key in conditions:
conditions_variable += key + "= %s and "
conditions_values.append(conditions[key])
sql = "update " + table_name + " set " + data_variable[:-1] + " where " + conditions_variable[:-4]
self.cur.execute(sql, data_values + conditions_values)
self.conn.commit()
except:
print("更新失败")
def delete_handle(self, table_name, **conditions):
#delete from student where name ="haha"
# print(conditions)
try:
if conditions == {}:
sql = "delete from "+table_name
self.cur.execute(sql)
else:
conditions_variable = ""
conditions_values = []
for key in conditions:
conditions_variable += key + "=%s and "
conditions_values.append(conditions[key])
sql = "delete from " + table_name + " where "+conditions_variable[:-4]
self.cur.execute(sql, conditions_values)
# 提交事务
self.conn.commit()
except:
print("删除失败")
def __del__(self):
# 关闭游标
self.cur.close()
# 关闭链接
self.conn.close()
if __name__ == '__main__':
mh = MysqlHandle('local', 0)
print(mh.select_handle('users'))
# user_dict = {
# 'user_id': '10',
# 'first_name': '23',
# 'last_name': '3',
# 'user': '3',
# 'password': '3',
# 'avatar': '3',
# 'last_login': '2019-09-10 16:37:32',
# }
# user_dict2 = {
# 'avatar': '3333',
# }
# mh.insert_test('users', user_dict)
# mh.update_test('users', user_dict2, user_id=8)
# mh.delete_test('auth_group', name=5)