我是python的新手,我创建了一个脚本来从postgreSQL中基于模式的表中选择数据。
但每当我运行脚本时,得到以下错误。有人对此有任何建议吗?
**Error while fetching data from PostgreSQL relation "public.sample" does not exist**
下面是我正在使用的脚本,我在这段代码中面临以下问题。 1.无法从模式内部的表中进行选择(如上所述).2。有一部分要在脚本中创建表,即使它正在运行,也不会在数据库中创建TABLE。 3.如果有人可以指导我使用Jinja2(目前数据值即将来临)创建一个HTML页面,在HTML脚本中,但对如何为多个用户执行此操作有疑问,那将非常有用。
import psycopg2
import jinja2
from collections import namedtuple
TEMPLATE="""
<!DOCTYPE html>
<html><head><title>Jinja Template Example</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" media="screen">
<style type="text/css">
.container {max-width: 500px;padding-top: 100px;}</style></head>
<body>
<div class="container">
<p>My string: {{my_string}}</p>
<p>Value from the list:</p>
<p>Loop through the list:</p>
<ul>
{% for row in rows %}
<p style="line-height: 14px; text-align: center; font-size: 12px; margin: 0;"> {{ row.column1 }}</p><br>
{% endfor %}
</ul>
</div>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstr
ap/3.0.0/js/bootstrap.min.js"></script>
</body>
</html>
"""
def dB_Fetch():
try:
connection = psycopg2.connect(user="postgres",
password="postgres",
host="127.0.0.1",
port="5432",
database="postgres")
cursor = connection.cursor()
print("Connection established")
cursor.execute("select version()")
version = cursor.fetchone()[0]
print(version)
cursor.execute("DROP TABLE IF EXISTS cars")
cursor.execute("CREATE TABLE cars(id SERIAL PRIMARY KEY, name VARCHAR(255), price INT)")
cursor.execute("INSERT INTO cars(name, price) VALUES('Audi', 52642)")
cursor.execute("INSERT INTO cars(name, price) VALUES('Mercedes', 57127)")
cursor.execute("INSERT INTO cars(name, price) VALUES('Skoda', 9000)")
cursor.execute("INSERT INTO cars(name, price) VALUES('Volvo', 29000)")
cursor.execute("INSERT INTO cars(name, price) VALUES('Bentley', 350000)")
cursor.execute("INSERT INTO cars(name, price) VALUES('Volkswagen', 21600)")
print("Table created")
postgreSQL_select_Query = "select * from public.Sample"
cursor.execute(postgreSQL_select_Query)
print("Selecting rows from test table using cursor.fetchall")
a = list();
print("Print each row and it's columns values")
env = jinja2.Environment()
template = env.from_string(TEMPLATE)
cursor.execute("SELECT Name FROM public.Sample;")
row_tuple = namedtuple("Row", [col[0] for col in cursor.description])
result = template.render(rows=[row_tuple(row) for row in cursor.fetchall()])
print (TEMPLATE)
print (result)
except (Exception, psycopg2.Error) as error:
print ("Error while fetching data from PostgreSQL", error)
finally:
if(connection):
cursor.close()
connection.close()
print("PostgreSQL connection is closed")
if __name__ == '__main__':
dB_Fetch()
问题在于架构和表的名称
public.Sample在您的数据库中不存在。请检查模式和表的确切名称,也可以在没有模式的情况下尝试,因此它应该自动指向公共模式。