下面的connect()函数连接到suppliers数据库并打印出 PostgreSQL 数据库版本。 importpsycopg2fromdemo.pgdemo.configimportconfigdefconnect():""" Connect to the PostgreSQL database server """conn =Nonetry:# read connection parametersparams = config()# connect to the PostgreSQL serverprint('Connecting to th...
connection = psycopg2.connect(user="your_username", password="your_password", host="127.0.0.1", port="5432", database="your_database") cursor = connection.cursor()print("Connected to PostgreSQL database!")except(Exception, psycopg2.Error)aserror:print("Error while connecting to PostgreSQL", ...
importpsycopg2try:connection=psycopg2.connect(user="your_username",password="your_password",host="127.0.0.1",port="5432",database="your_database")cursor=connection.cursor()print("Connected to PostgreSQL database!")except(Exception,psycopg2.Error)aserror:print("Error while connecting to PostgreSQL",...
importpsycopg2# 连接到 PostgreSQL 数据库conn=psycopg2.connect(dbname="your_database_name",user="your_username",password="your_password",host="your_host",port="your_port")# 创建一个游标对象cur=conn.cursor()# 执行 SQL 查询cur.execute("SELECT * FROM your_table_name;")# 获取查询结果rows=cur...
[postgresql] host=localhost database=suppliers user=postgres password=postgres 3. 放在一起:connect代码块 首先写config()函数,这一函数会读取配置文件database.ini来获取文件中用于数据库连接的参数. 我们可以保存以下代码块在config.py文件中,以便之后的重复调用。
Postgresql & psycopg2: database does not exist I am trying to establish a connection to a database like this: psycopg2.connect(database="movies", user="lfcj", host="127.0.0.1"); mypg_hba.conffile has a line: TYPE __ DATABASE___USER__ADDRESS___METHOD...
fromsqlalchemyimportcreate_enginefrompostgis.psycopgimportregisterfromurllibimportparsefromurllib.parseimportquote_plusasurlquotecon_str=f"postgresql+psycopg2://{username}:{urlquote(password)}@{host}:{port}/{database}"con=create_engine(con_str,max_overflow=50,# 超过连接池大小外最多创建的连接pool_si...
import psycopg2 try: conn = psycopg2.connect("dbname='template1' user='dbuser' host='localhost' password='dbpass'") except: print "I am unable to connect to the database" cur = conn.cursor() cur.execute("""SELECT datname from pg_database""")优点 快速高效。支持多种连接、以及...
querycur.execute('SELECT version()')# Print Resultdb_version=cur.fetchone()print(db_version)# close the communication with the PostgreSQLcur.close()except(Exception)aserror:print(error)finally:ifconnisnotNone:conn.close()print('Database connection closed.')if__name__=='__main__':connect(...
importpsycopg2try:connection=psycopg2.connect(user="your_username",password="your_password",host="127.0.0.1",port="5432",database="your_database")cursor=connection.cursor()print("Connected to PostgreSQL database!")except(Exception,psycopg2.Error)aserror:print("Error while connecting to PostgreSQL",...