1. 程式人生 > >資料庫連結2

資料庫連結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')