繁体   English   中英

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

[英]Selecting data using psycopg2 from a schema based table in PostgreSQL

我是 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 在您的数据库中不存在。 请检查架构和表的确切名称,您也可以尝试不使用架构,因此它应该自动指向公共架构。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM