使用Python连接到Postgres sql

时间:2018-02-09 09:38:31

标签: python postgresql docker

我在docker容器上运行postgressql。我试图通过python连接到postgres并显示下面的表格是我用来连接到postgres的代码:

import psycopg2

conn_string = "host='192.168.99.100:15432' dbname='PREDICTIVE_DS_POSTGRESQL' 
user='ds_user' password='ds_user'"
print("Connecting to database\n ->%s" % (conn_string))
conn = psycopg2.connect(conn_string)
cursor = conn.cursor()
print("Connected!\n")

然后我使用下面的Python代码来显示postgres中的现有表:

def table_exists(con, table_str):

exists = False
try:
    cur = con.cursor()
    cur.execute("select exists(select relname from pg_class where relname='" 
    + table_str + "')")
    exists = cur.fetchone()[0]
    print("exists")
    cur.close()
    except psycopg2.Error as e:
    print(e)
    return exists

    def get_table_col_names(con, table_str):

    col_names = []
  try:
    cur = con.cursor()
    cur.execute("select * from " + table_str + " LIMIT 0")
    for desc in cur.description:
        col_names.append(desc[0])
    cur.close()
except psycopg2.Error as e:
    print(e)

然而,它根本不起作用。它说它无法将转换主机名“192.168.99.100:15432”连接到地址:未知主机。但是,容器已启动并正在运行,这是主机名。另外,我不知道其他代码在连接后是否会起作用。

1 个答案:

答案 0 :(得分:0)

在单独的文件中定义数据库凭据。

例如,有一个名为database.ini的文件,并按如下方式定义:

[creds]
host=192.168.99.100
port=15432
database=PREDICTIVE_DS_POSTGRESQL
user=ds_user
password=ds_user

有另一个配置解析器文件来解析它。称之为config.py

#!/usr/bin/python
try:
    import configparser
except:
    from six.moves import configparser


def config(section,filename='database.ini',):
    parser = configparser.ConfigParser()
    parser.read(filename)
    db = {}
    if parser.has_section(section):
        params = parser.items(section)
        for param in params:
            db[param[0]] = param[1]
    else:
        raise Exception('Section {0} not found in the {1} 
file'.format(section, filename))
    return db

现在,在您的主文件中,导入您的配置功能:

from config import config

并像这样连接:

    dbParams = config("creds")
    con = psycopg2.connect(**dbParams)