前沿
对mysql操控的几行代码总结,增删改查。
import pymysql
from sqlalchemy import create_engine
import pandas as pd
import numpy as np
class use_mysql(object):
# con = pymysql.connect(**config)
# mycursor = con.cursor()
def __init__(self,config=None):
if config is None:
# 连接数据库
config = {
'user': 'root',
'password': '12345',
'host': '127.0.0.1',
'port': 3306,
'database': 'supcon'
}
self.config=config
self.name='zwl'
self.con=pymysql.connect(**self.config)
self.mycursor=self.con.cursor()
# 判断表是否存在
def existsTable(self, tb_name):
stmt = "SHOW TABLES LIKE '{}'".format(tb_name)
self.mycursor.execute(stmt)
res=self.mycursor.fetchone()
if res:
stats='exists'
else:
stats='not exists'
return stats
# 删除表
def dropTable(self, tb_name):
stmt = "DROP TABLE IF EXISTS {} ".format(tb_name)
self.mycursor.execute(stmt)
return True
# 创建表
def createTable(self, tb_name,df):
type_category = {'int64': 'int', 'string': 'char(255)', 'float': 'double'}
field = []
for col in df.columns:
type = str(df[col].dtypes)
field.append('{} {}'.format(col, type_category[type]))
field = ",".join(field)
stmt = '''create TABLE {}\n({}) '''.format(tb_name,field)
print('create sql:',stmt)
self.mycursor.execute(stmt)
return True
#存储数据到mysql
def writeTable(self,tb_name,df):
config=self.config
user,pswd,url,database=config['user'],config['password'],config['host'],config['database']
charset='utf8'
conn='mysql+pymysql://{}:{}@{}/{}?charset={}'.format(user,pswd,url,database,charset)
engine=create_engine(conn, encoding='utf-8')
df.to_sql(name=tb_name, con=engine, if_exists='append', index=False, index_label=False)
return True
# 读mysql表内容
def get_mysql_data(self,sql):
cur=self.mycursor
conn=self.con
try:
cur.execute(sql)
index = cur.description
field_names = [field[0] for field in index]
record = cur.fetchall()
if len(record)>0:
df = pd.DataFrame(list(record))
else:
df=pd.DataFrame(['']*len(field_names))
df.columns = field_names
except:
df = ''
cur.close()
return df