数据库链接2

import pymysql
import pandas as pd
from pandas import DataFrame
from sqlalchemy import create_engine

class mysql_qiao():
def __init__(self,host,port,user,password,database):
self.host=host
self.port=port
self.user=user
self.password=password
self.database=database
self._conn = None
self.Connect()

def Connect(self):
if not self._conn:
self._conn=pymysql.connect(host=self.host,port=self.port,user=self.user,password= self.password,database=self.database,charset='utf8')


#查询数据库表中的所有数据
def Query(self,sql):
if self.Connect():
pass
else:
self.Connect()
self.cursor = self._conn.cursor()
self.excute = self.cursor.execute(sql)

row_all = self.cursor.fetchall()
index = self.cursor.description
new_index=[]
for i in range(len(index)):
new_index.append(index[i][0])
data_sql=DataFrame(list(row_all),columns=new_index)

return data_sql
def Exec(self, sql):
"""
对数据库执行增、删、改操作,传入需要执行的SQL语句
"""
if self.Connect():
pass
else:
self.Connect()
self.cursor = self._conn.cursor()

self.cursor.execute(sql)
# self._conn.commit()


#数据保存到数据库
def my_keep(self,data,filename):
if self.Connect():
pass
else:
self.Connect()
db_url = (
'{driver}://{user}:{pwd}@{host}:{port}/{name}?charset=utf8'.format(driver='mysql+pymysql', user=self.user,
port=self.port, pwd=self.password,
host=self.host, name=self.database))
my_engine = create_engine(db_url)
pd.io.sql.to_sql(data, filename, my_engine, schema=self.database, if_exists='append', index=False,index_label=False)
self.my_close()
def my_close(self):
self.cursor.close()
self._conn.close()


from sqlalchemy import create_engine
import numpy as np
import pandas as pd
import pymysql
import sys
sys.path.append("../")

from mysql import *





if __name__ == '__main__':


pym=mysql_qiao(host='', port=3306, user='',
password='', database='')

statistics_sql='select * from algorithm.cam_statistics where total_id={0} and category_manual={1}'.format(1,0)
statistics_data=pym.Query(statistics_sql)
print('statistics_data',statistics_data)


#插入数据
nick='jackjones官方旗舰'
price=15000
date_str='2018-06-21'
insert_sql="insert into algorithm.cam_parameter(nick,budget,date_str) values ('{0}',{1},'{2}')".format(nick,price,date_str)
pym.Exec(insert_sql)

#跟新数据
name='jack'
update_sql="update algorithm.cam_parameter set nick='{0}' where id={1}".format(name,3)
pym.Exec(update_sql)

#删除数据
del_sql='delete from algorithm.cam_parameter where id={0}'.format(3)
pym.Exec(del_sql)

#保存数据
df=pd.DataFrame({
'nick':['m1','m2'],
'budget':[1000,2000],
'date_str':['2018-10-10','2018-10-12']
})
pym.my_keep(df,'cam_parameter')










猜你喜欢

转载自www.cnblogs.com/hapyygril/p/9805837.html
今日推荐