sco*_*loe 5 python path mysql-python dataframe pandas
这是一个我无法找到答案的简单问题.我有一个带有两个命令的.SQL文件.我想让Pandas将这些命令的结果拉入DataFrame.
SQL文件的命令就是这样,使用今天的日期查询时间更长.
SET @todaydate = DATE(NOW());
SELECT ...long query....;
Run Code Online (Sandbox Code Playgroud)
在建立连接(prod_db)后,我尝试以下列方式使用read_sql并获取错误消息''NoneType'对象不可迭代'
sqlpath = 'path.sql'
scriptFile = open(sqlpath,'r')
script = scriptFile.read()
df = pd.read_sql(script,prod_db)
Run Code Online (Sandbox Code Playgroud)
我也尝试使用这里描述的函数和方法在python中读取外部sql脚本,但我不确定如何将结果导入pandas数据帧(或者我可能缺少某些东西).它似乎没有读取结果,因为我反复得到'命令跳过'.
def executeScriptsFromFile(filename):
fd = open(filename, 'r')
sqlFile = fd.read()
fd.close()
# all SQL commands (split on ';')
sqlCommands = sqlFile.split(';')
# Execute every command from the input file
for command in sqlCommands:
try:
c.execute(command)
except OperationalError, msg:
print "Command skipped: ", msg
df = executescriptsfromfile(sqlpath)
Run Code Online (Sandbox Code Playgroud)
Geo*_*eof 18
我有一个可能适合你的解决方案.它应该给你一个很好的一点pandas.DataFrame.
首先,您必须阅读sql文件中的查询.然后只需使用pd.read_sql_query()而不是pd.read_sql()
我相信你知道,但这里是该函数的文档:http://pandas.pydata.org/pandas-docs/version/0.20/generated/pandas.read_sql_query.html#pandas.read_sql_query
# Read the sql file
query = open('filename.sql', 'r')
# connection == the connection to your database, in your case prob_db
DF = pd.read_sql_query(query.read(),connection)
Run Code Online (Sandbox Code Playgroud)
我可以向你保证它正在使用T-SQL,但我从未在MySQL上使用它.
这是 MWE,它对我来说是如何工作的:
query = open('./query_file.sql', 'r')
db_config = {
'server': server address,
'port': port,
'user': user,
'password': password,
'database': db name
}
try:
sql_conn = pymssql.connect(**db_config)
logging.info('SQL connection is opened')
avise_me_df = pd.read_sql(query.read(),sql_conn)
logging.info('pandas df recorded')
except OperationalError as e:
connected = False
logging.error('Error reading data from SQL table')
else:
connected = True
finally:
if connected:
sql_conn.close()
logging.info('SQL connection is closed')
Run Code Online (Sandbox Code Playgroud)
我希望这会有所帮助。
| 归档时间: |
|
| 查看次数: |
20777 次 |
| 最近记录: |