使用 Python 在 Datalore 中运行 sqlite 数据检索语句时出错

Error running sqlite data retrieve statement in Datalore with Python

提问人:user3087182 提问时间:6/29/2022 最后编辑:forpasuser3087182 更新时间:6/29/2022 访问量:78

问:

这个用于 sqlite db 的 Python 代码在 Datalore 中失败,我无法弄清楚原因。数据库已正确连接,并且其他脚本正在运行。

gdpquery= '''SELECT  C.Country_Area, G.Year, I.Indicator G.Value FROM Countries C, GDP G, Indicators I
WHERE AND(C.CA_M49_Code = G.CA_M49_Code, G.Ind_No = I.Ind_No, G.Ind_Type_No = I.Ind_Type_No)'''

gdpdata = pd.read_sql_query(gdpquery, conn)

gdpdata.head(4)

错误:

Traceback (most recent call last):

  at block 10, line 3

  at /opt/python/envs/default/lib/python3.8/site-packages/pandas/io/sql.pyline 436, in read_sql_query(sql, con, index_col, coerce_float, params, parse_dates, chunksize, dtype)

  at /opt/python/envs/default/lib/python3.8/site-packages/pandas/io/sql.pyline 2116, in read_query(self, sql, index_col, coerce_float, params, parse_dates, chunksize, dtype)

  at /opt/python/envs/default/lib/python3.8/site-packages/pandas/io/sql.pyline 2068, in execute(self, *args, **kwargs)

DatabaseError: Execution failed on sql 'SELECT C.Country_Area, G.Year, I.Indicator G.Value FROM Countries C, GDP G, Indicators I WHERE AND(C.CA_M49_Code = G.CA_M49_Code, G.Ind_No = I.Ind_No, G.Ind_Type_No = I.Ind_Type_No)': near ".": syntax error

screenshot on retrying as per comments

python sqlite 联接 和运算符 datalore

评论

1赞 buran 6/29/2022
AND是 SQL 语法中的运算符,而不是函数

答:

1赞 forpas 6/29/2022 #1

这:

WHERE AND(C.CA_M49_Code = G.CA_M49_Code, G.Ind_No = I.Ind_No, G.Ind_Type_No = I.Ind_Type_No)

不是有效的 SQLite(或一般的 SQL)语法。
它应该是:

WHERE C.CA_M49_Code = G.CA_M49_Code AND G.Ind_No = I.Ind_No AND G.Ind_Type_No = I.Ind_Type_No

但是,表达逻辑的正确方法是使用 ON 子句进行适当的连接:

SELECT C.Country_Area, G.Year, I.Indicator, G.Value 
FROM Countries C 
INNER JOIN GDP G ON C.CA_M49_Code = G.CA_M49_Code
INNER JOIN Indicators I ON G.Ind_No = I.Ind_No AND G.Ind_Type_No = I.Ind_Type_No; 

评论

0赞 user3087182 6/29/2022
这很有帮助,但适当地放置 AND 运算符并使用 JOIN、ON 替代方案似乎并不能解决问题。根据我上面编辑的帖子,我添加了屏幕截图,弹出了相同的错误。IDE 将行“gdpdata = pd.read_sql_query(gdpquery, conn)”指向包含错误的行,但我知道它可能是任何其他行。
0赞 forpas 6/29/2022
@user3087182我在查询中错过了 I.Indicator 和 G.Value 之间的一个。立即检查。,