使用psycopg2从PostgreSQL中基于模式的表中选择数据

时间:2019-04-28 19:27:18

标签: python postgresql jinja2 psycopg2

我是python的新手,我创建了一个脚本来从PostgreSQL中基于模式的表中选择数据。

但是每当我运行脚本时,都会出现以下错误。有人对此有任何建议吗?

**Error while fetching data from PostgreSQL relation "public.sample" does not exist**

下面是我正在使用的脚本, 我在此代码中面临以下问题。     1.无法从架构内部的表中选择(如上所述)     2.在脚本中有一部分可以创建表,即使它正在运行,也不会在数据库中创建表。    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()

1 个答案:

答案 0 :(得分:0)

问题在于模式和表的名称

public.Sample在您的数据库中不存在。 请检查模式和表的确切名称,也可以不使用模式而尝试,这样它应该自动指向公共模式。