数据库操作
2021-10-13 本文已影响0人
无谓着
import pymysql
class mysql_db():
def __init__(self,host,user,password,port,database):
self.con = pymysql.connect(
host=host,
user=user,
password=password,
port=port, # 默认即为3306
database=database,
charset='utf8',
)
self.cursor = self.con.cursor()
def select_sql(self,sql,type):
#传入查询类型,0查询一条数据,1查询所有数据
self.cursor.execute(sql)
if type==1:
result_all = self.cursor.fetchall()
self.cursor.close()
self.con.close()
return result_all
elif type==0:
result_one = self.cursor.fetchone()
self.cursor.close()
self.con.close()
return result_one
def insert_sql(self,sql):
try:
self.cursor.execute(sql)
self.con.commit()
except Exception as e:
self.con.rollback()
print(e)
finally:
self.cursor.close()
self.con.close()
def update_sql(self,sql):
try:
self.cursor.execute(sql)
self.con.commit()
except Exception as e:
self.con.rollback()
print(e)
finally:
self.cursor.close()
self.con.close()
def delete_sql(self,sql):
try:
self.cursor.execute(sql)
self.con.commit()
except Exception as e:
self.con.rollback()
print(e)
finally:
self.cursor.close()
self.con.close()
if __name__=="__main__":
host = '' # 默认127.0.0.1
user = ''
password = ''
port = 3308 # 默认即为3306
database = ""
con = mysql_db(host,user,password,port,database)
# sql = 'select * from tb_user limit 10;'
sql = "select b.liquidity from tb_cfd_position_ethusdt as a,tb_cfd_delegate_deal_record_ethusdt as b where b.order_id=a.order_id and a.id='333' and b.user_id='10024' and b.delegate_type in (1,2);"
s = con.select_sql(sql,0)[0]
print(s)