使用Python在Qgis中连接PostgreSql数据库的问题

时间:2019-05-16 10:16:35

标签: qgis

我正在跟踪http://www.postgresqltutorial.com/postgresql-python/connect/,以连接Qgis3.4版本的postgresql数据库,但没有收到数据库的任何响应。

#database.ini file

[postgresql]
host='192.168.10.250'
database='kseb_final'
user='postgres'
password='post123'
#config.py file

from configparser import ConfigParser

def config(filename='database.ini', section='postgresql'):
    # create a parser
    parser = ConfigParser()
    # read config file
    parser.read(filename)

    # get section, default to postgresql
    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
#connection.py File

#!/usr/bin/python
import psycopg2
from config import config

def connect():
    """ Connect to the PostgreSQL database server """
    conn = None
    try:
        # read connection parameters
        params = config()

        # connect to the PostgreSQL server
        print('Connecting to the PostgreSQL database...')
        conn = psycopg2.connect(**params)

        # create a cursor
        cur = conn.cursor()

 # execute a statement
        print('PostgreSQL database version:')
        cur.execute('SELECT version()')

        # display the PostgreSQL database server version
        db_version = cur.fetchone()
        print(db_version)

     # close the communication with the PostgreSQL
        cur.close()
    except (Exception, psycopg2.DatabaseError) as error:
        print(error)
    finally:
        if conn is not None:
            conn.close()
            print('Database connection closed.')


if __name__ == '__main__':
    print("Hi i am here")
    connect()

我得到的结果如下: exec(open('C:/Users/USER/AppData/Local/Temp/tmp2yl0cyo4.py'.encode('utf-8')。read())

除上述以外,我什么都没得到。至少应打印“嗨,我在这里”。但是,它没有任何打印。请告诉我我的代码有什么问题。我是qgis新手。

0 个答案:

没有答案