使用pymysql,从mysql查询数据,返回结果是tuple类型
def query_kdata(self,code):
if self.connect is None:
return None
# 得到一个可以执行SQL语句的光标对象
cursor = self.connect.cursor()
# sql语句,DESC降序,ASC升序
sql = "select open,close,high,low,vol,trade_day from t_kdata where code = %s order by trade_day ASC;"
print(code+">>>"+sql)
try:
# 执行SQL语句
cursor.execute(sql, (code,))
# 把修改的数据提交到数据库
self.connect.commit()
result = cursor.fetchall()
# 关闭光标对象
cursor.close()
return result
except Exception as e:
# 捕捉到错误就回滚
self.connect.rollback()
print(e)
return None
执行select以后,返回结果result是tuple类型
result = cursor.fetchall()
上层应用需要将result转换成dataframe,进行算术移动平均值等算术处理:
#将需要处理的数据,从mysql数据库读出来,转换成DataFrame进行处理
#根据sql语句的select内容,进行转换
def Mysql2DataFrame(self, code):
result = self.db.query_kdata(code)
df = pd.DataFrame(list(result), columns=["open", "close", "high", "low", "vol", "trade_day"])
#print(df)
return df
注意:columns的值,与select中的值,一一对应关系。
获取dataframe列中的值:
df = self.Mysql2DataFrame(code)
all_vol = df['vol']
all_close = df['close']
all_trade_day = df['trade_day']