如何解决为什么选择查询通过python引发语法错误?
我正在尝试连接到Postgres数据库并执行一个简单的select查询。但是我遇到了错误。下面是示例程序
import psycopg2 as ps
param_dic = ps.connect(
host="localhost",database="Test_DB",user="username",password="password"
)
cur = param_dic.cursor()
cur.execute("select * from <schema_name>.'employee_tbl'") # I am
rows = cur.fetchall()
for r in rows:
print(r)
我得到以下错误:
psycopg2.errors.SyntaxError: syntax error at or near "'tbl_name'"
LINE 1: select * from <schema_name>.'tbl_name'
如果我使用
cur.execute("select * from <schema_name>.'Employee_TBL'")
仍然,我遇到同样的错误。
注意:当我检查pgAdmin时,我在下面看到表名
<schema_name>.Employee_TBL
那么,在Postgres表上执行SQL查询的正确方法是什么?
解决方法
用真实值替换
也许只是一个错字,如果需要,可以在表中使用双引号。
单引号表示字符串文字。
import psycopg2
conn = psycopg2.connect(...)
cur = conn.cursor()
cur.execute('SELECT * FROM public.servers')
print(len(cur.fetchall()))
cur.execute('SELECT * FROM PUBLIC."servers"')
print(len(cur.fetchall()))
出局:
6
6
,
尝试删除“ emloyee_tbl”周围的引号
,最重要的问题是,您创建了一个表名,并带有混合大小写的引号。这意味着从那时起,您需要引用名称才能使用它:
create table "Mixed_Case" (id int,fld_1 varchar);
select * from mixed_case;
ERROR: relation "mixed_case" does not exist
LINE 1: select * from mixed_case;
select * from "Mixed_Case";
id | fld_1
----+-------
(0 rows)
--NOTE the double quotes.
有关更多信息,请参见4.1.1. Identifiers and Key Words
对于psycopg2情况:
import psycopg2
con = psycopg2.connect("dbname='test' host='localhost' user='aklaver'")
cur = con.cursor()
# Single quoted
cur.execute("select * from public.'Mixed_Case'")
SyntaxError: syntax error at or near "'Mixed_Case'"
LINE 1: select * from public.'Mixed_Case'
# Identifiers need double quotes
# Changing to double quotes
cur.execute('select * from public."Mixed_Case"')
# No error.
# You can also use Postgres functions
cur.execute("select * from quote_ident('public.Mixed_Case')")
有关Postgres函数和方法的更多信息,请参见string functions
在psycopg2中,还有一个sql模块,允许您使用标识符:
from psycopg2 import sql
sql_str = sql.SQL("select * from public.{}").format(sql.Identifier('Mixed_Case'))
print(sql_str.as_string(con))
select * from public."Mixed_Case"
cur.execute(sql_str)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。