gpt4 book ai didi

python - Google BigQuery - Python 查询未正确解析

转载 作者:行者123 更新时间:2023-11-30 22:52:21 25 4
gpt4 key购买 nike

我正在尝试使用 Python API 设置一个简单的 Google BigQuery 应用程序。我按照快速入门指南进行操作:

import argparse

from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from oauth2client.client import GoogleCredentials


def main(project_id):
print "hello"
# [START build_service]
# Grab the application's default credentials from the environment.
credentials = GoogleCredentials.get_application_default()
# Construct the service object for interacting with the BigQuery API.
bigquery_service = build('bigquery', 'v2', credentials=credentials)
# [END build_service]

query_request = bigquery_service.jobs()
query_data = {
'query': (
'SELECT ticker,close1'
'FROM Data.data_7 '
'WHERE ticker = "GTIM"'
'LIMIT 10')
}

query_response = query_request.query(
projectId=project_id,
body=query_data).execute()

print('Query Results:')
for row in query_response['rows']:
print('\t'.join(field['v'] for field in row['f']))


main("sqlserver-1384")

并且能够成功运行上述查询。但是每当我将其更改为:

   'query': (
'SELECT ticker,close1'
'FROM Data.data_7 '
'ORDER BY close1 ASC'
'LIMIT 10')
}

我收到以下错误:

Traceback (most recent call last):
File "server1.py", line 57, in <module>
main("sqlserver-1384")
File "server1.py", line 50, in main
body=query_data).execute()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/oauth2client/util.py", line 135, in positional_wrapper
return wrapped(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/googleapiclient/http.py", line 832, in execute
raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://www.googleapis.com/bigquery/v2/projects/sqlserver-1384/queries?alt=json returned "Encountered " <ID> "ASCLIMIT "" at line 1, column 54.
Was expecting:
<EOF>">

我的格式有问题吗?我在 Google BigQuery Web Console 上运行了相同的查询,效果很好。

谢谢

最佳答案

当 python 解析器连接查询字符串时,您会留下单词 ASCLIMIT,它不是有效的 BQ SQL。在查询中的 ASC 之后添加一个空格,应该没问题。

{
'query': (
'SELECT ticker,close1 ' # Space at the end of this line too
'FROM Data.data_7 '
'ORDER BY close1 ASC ' # Space at the end of this line
'LIMIT 10')
}

或者,使用三重引号字符串编写查询:

'''
SELECT ticker, close1
FROM Data.data_7
ORDER BY close1 ASC
LIMIT 10
'''

此时换行符将被保留。

关于python - Google BigQuery - Python 查询未正确解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38617633/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com