一、環境準備
- mysql安裝 https://mp.csdn.net/postedit/81771687
- 下載依賴包 pip3 install pymysql
二、接口調用
以下羅列兩種實現方式,第一種是原生的;第二種就是集成pandas的,用起來很方便,就跟mybatis一樣。
第一種:
- configuration.properties
[SQL]
sql_host:172.8.10.xx
sql_port:3306
sql_db:xx
sql_username:xx
sql_password:xx
- MysqlClient
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
import json
import pymysql
config=ConfigParser()
config.read(str(config_file['configPath'].iloc[0]))
# =============================================================================
# initialization
# =============================================================================
SQL_host = config.get('SQL', 'SQL_host')
SQL_port = config.getint('SQL', 'SQL_port')
SQL_username = config.get('SQL', 'SQL_username')
SQL_password = config.get('SQL', 'SQL_password')
SQL_db = config.get('SQL', 'SQL_db')
class MysqlClient:
def __init__(self):
self.connection = pymysql.Connect(host=SQL_host, port=SQL_port,
user=SQL_username, passwd=SQL_password,
db=SQL_db, charset='utf8')
self.cursor = self.connection.cursor()
def insert(self, query):
try:
self.cursor.execute(query)
self.connection.commit()
except Exception as e:
# self.connection.rollback()
raise Exception(e)
finally:
self.cursor.close()
self.connection.close()
def query(self, query):
try:
cursor = self.connection.cursor(pymysql.cursors.DictCursor)
cursor.execute(query)
return cursor.fetchall()
except Exception as e:
raise Exception(e)
finally:
self.cursor.close()
self.connection.close()
第二種:
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
import json
import pandas as pd
conn_Mysql = create_engine("mysql+pymysql://{SQL_username}:{SQL_password}@{SQL_host}:{SQL_port}/{SQL_db}".format(
SQL_username=SQL_username, SQL_password=SQL_password,
SQL_host=SQL_host, SQL_port=SQL_port, SQL_db=SQL_db))
案例:
sql_query = '''select alarm_time from xx
where machine_id={mid} and spindle_name={sid}
and cutter_location_name={tn} and program_no="{pn}"
'''.format(mid=machineID, sid=spindleID, tn=toolNum, pn=programNum)
histAlarmTime = pd.read_sql(sql_query, conn_Mysql)