ppython执行一段python代码,作用是完成数据库连接并查询生成dataframe。执行一次后,更新数据库内容,再次执行这段python代码,发现数据库更新不能反映到dataframe中。
原来代码:
db = pymysql.connect(host='localhost', port=3306, user='root', passwd='***', db='ultrax', charset='utf8')
# 创建游标
cursor = db.cursor()
sql = 'SELECT c_qx,c_rk FROM pre_cat_dyrk'
cursor.execute(sql)
result = cursor.fetchall()
# 关闭连接
db.close()
#执行结果转化为dataframe
df = pd.DataFrame(list(result))
以上代码写入函数中,问题解决:
def get_df():
db = pymysql.connect(host='localhost', port=3306, user='root', passwd='***', db='ultrax', charset='utf8')
# 创建游标
cursor = db.cursor()
sql = 'SELECT c_qx,c_rk FROM pre_cat_dyrk\
'
cursor.execute(sql)
result = cursor.fetchall()
# 关闭连接
db.close()
#执行结果转化为dataframe
df = pd.DataFrame(list(result))
return df