数据库学习之将mysql的insert和select操作封装成类
作者:互联网
import pymysql
class MyMysql:
def __init__(self):
mysql_config = {
'host':'127.0.0.1',
'port':3306,
'user':'root',
'password':'qwe123',
'db':'wumou',
'charset': 'utf8'
}
self.conn = pymysql.connect(**mysql_config)
self.cur = self.conn.cursor()
def insert(self,tbname,*args):
'''注意在mysql中,insert语句:insert into tbname values(1,'wuhan',14)
所以在python操作mysql的insert语句时,要注意将value转换为括号里面放值
且整个value为字符串类型'''
args = list(args)
for i in range(len(args)):
args[i] = tuple(args[i])
args = str(args)
st = args[1:-1]
sql = f'insert into {tbname} value {st}'
self.cur.execute(sql)
def select(self,field,tbname,select_var = 1,**condition):
'''python操作mysql数据库进行查询操作
tbname为表名;select_var默认形参为1时是有一个条件查询,为2时是无条件查询,为3是多条件查询
condition为条件'''
if select_var == 1:
for key,value in condition.items():
condition_new = f"where {key} = '{value}'"
sql = f'select {field} from {tbname} {condition_new}'
elif select_var ==2:
sql = f'select {field} from {tbname}'
else:
a = [] #将条件(字典类型)变为列表类型
for key,value in condition.items():
a.extend([key,value])
b = [] #将每个条件中的字段与值用=相连
for i in range(len(a)):
if i % 2 == 0:
b.append(f"{a[i]} = '{a[i+1]}")
b = str(b)
#切出有用的条件语句
b = b.replace('", "'," 'and ")
print('第二次b ',b)
sql = f"select {field} from {tbname} where {b[2:-2]}'"
self.cur.execute(sql)
for i in self.cur:
print(i)
#mysql的update和delete方法主要思路如上!!!
def update(self):
pass
def delete(self):
pass
def close(self):
self.conn.commit()
self.conn.close()
self.cur.close()
m = MyMysql()
# m.insert('student',[8,'吴某',2,54,'third'],[9,'中国',3,57,'first'])
m.select('*','student',select_var=3,name = 'zhongguo',age = 18,gradname = 'first')
m.close()
所操作的mysql表示例:
标签:insert,成类,self,args,tbname,mysql,select 来源: https://blog.csdn.net/qq_44907926/article/details/104541234