我将read_sql方法中转换为字符串的元组作为
sql = "select * from table1 where col1 in " + str(tuple1) + " and col2 in " + str(tuple2)
df = pd.read_sql(sql, conn)这可以很好地工作,但是,当元组只有一个值时,sql会失败,返回ORA-00936: missing expression,因为单个元素元组有一个额外的逗号
例如
tuple1 = (4011,)
tuple2 = (23,24)形成的sql格式为
select * from table1 where col1 in (4011,) + " and col2 in (23,24)
^
ORA-00936: missing expression除了使用字符串操作删除逗号之外,还有什么更好的方法吗?
有没有更好的方法来参数化read_sql函数?
发布于 2017-09-04 23:17:47
可能有一种更好的方法,但我会在执行查询时添加一条if语句,并使用.format()而不是+来参数化查询。
可能的if语句:
if len(tuple1) < 2:
tuple1 = tuple1[0]这将根据您的输入内容而有所不同。如果你有一个元组列表,你可以这样做:
tuples = [(4011,), (23, 24)]
new_t = []
for t in tuples:
if len(t) == 2:
new_t.append(t)
elif len(t) == 1:
new_t.append(t[0])输出:
[4011, (23, 24)]使用.format()参数化查询的更好方法
sql = "select * from table1 where col1 in {} and col2 in {}".format(str(tuple1), str(tuple2))希望这能有所帮助!
发布于 2017-09-05 18:31:47
出现这个错误的原因是因为SQL语法。
当您有一个WHERE col in (...)列表时,后面的逗号将导致语法错误。
无论哪种方式,使用字符串连接将值放入SQL语句都是不受欢迎的,最终会导致更多的问题。
大多数Python SQL库都允许参数化查询。在不知道使用哪个库连接的情况下,我无法链接确切的文档,但psycopg2的原理是相同的:
http://initd.org/psycopg/docs/usage.html#passing-parameters-to-sql-queries
此功能在pd.read_sql中也是公开的,因此要安全地获得您想要的内容,您可以这样做:
sql = "select * from table1 where col1 in %s and col2 in %s"
df = pd.read_sql(sql, conn, params = [tuple1, tuple2])https://stackoverflow.com/questions/46039492
复制相似问题