You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
python-project/database/mysql.py

53 lines
1.9 KiB

import pymysql
class MySQLDB():
def __init__(self,*args,
host='localhost',
user='root',
password=None,
port=3306,
db='mysql',
charset='utf8',
):
self.conn = pymysql.connect(user=user,host=host,port=port,password=password,db=db,charset=charset,cursorclass=pymysql.cursors.DictCursor)
self.cursor = self.conn.cursor()
def DML(self,sql,condition,mode):
try:
if mode == 'insert':
if len(condition) > 1:
result = self.cursor.executemany(sql,condition)
else:
result = self.cursor.execute(sql, condition)
print(f'插入完成,受影响{result}')
if mode == 'update':
result = self.cursor.execute(sql)
print(f'更新完成,受影响{result}')
if mode == 'delete':
result = self.cursor.execute(sql)
print(f'删除完成,受影响{result}')
self.conn.commit()
except pymysql.MySQLError as e:
self.conn.rollback()
print(e)
finally:
self.conn.close()
def DQL(self,sql,size=None):
try:
result = self.cursor.execute(sql)
if size:
result2 = self.cursor.fetchmany(size)
else:
result2 = self.cursor.fetchall()
for i in result2:
for v in i.values():
print(v,end='\t')
print()
print(f'共查找{result}条记录')
except pymysql.MySQLError as e:
print(e)
finally:
self.conn.close()
def __str__(self):
return '详细操作手册查看 https://www.baidu.com'
a = MySQLDB(host='39.103.141.138',user='eval',password='123456',db='db1')
a.DQL('select id,name from user')