簡體   English   中英

從 Jupyter notebook 訪問本地 Postgresql 服務器

[英]Accessing local Postgresql server from Jupyter notebook

我在本地主機中托管了一個 postgresql 數據庫“Test2”。 我可以使用 pgAdmin 查看表。 我想從 Jupyter Notebook 獲取數據庫的數據。 我嘗試按照https://towardsdatascience.com/python-and-postgresql-how-to-access-a-postgresql-database-like-a 的“第 2 部分”中所示的步驟連接到數據庫-數據科學家-b5a9c5a0ea43

因此,我的代碼是——

import config as creds
import pandas as pd

def connect():
    
    # Set up a connection to the postgres server.
    conn_string = "host="+ creds.PGHOST +" port="+ "5432" +" dbname="+ creds.PGDATABASE +" user=" + creds.PGUSER \
                  +" password="+ creds.PGPASSWORD
    
    conn = psycopg2.connect(conn_string)
    print("Connected!")

    # Create a cursor object
    cursor = conn.cursor()
    
    return conn, cursor

#Connecting to DB
conn, cursor = connect()

#SQL command to create inventory table

abc = ("""SELECT * FROM clubs""")
#Execute SQL Command and commit to DB
cursor.execute(abc)
results = cursor.fetchall()
print(results)

conn.commit()

我的 config.py 看起來像這樣 -->

PGHOST = 'localhost'
PGDATABASE = 'Test2'
PGUSER = '#####'
PGPASSWORD = '#####'

當表名全部為小寫字符時,我能夠獲得輸出,但對於具有混合字符(如“clubCategory”)的表名,它會引發錯誤,指出“關系“clubcategory”不存在”

我試過

abc = ("""SELECT * FROM 'clubCategory' """)

但它仍然拋出錯誤。

請問有什么幫助嗎?

嘗試使用雙引號:

abc = ('''SELECT * FROM "clubCategory" ''')

另請參閱此答案: https : //stackoverflow.com/a/21798517/1453822

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM