使用Python第三方库psycopg2连接集群 需要连接的database user'dbadmin', password'password') 数据库用户密码 except psycopg2.DatabaseError as ex: print(ex) print("Connect database failed") else: print("Opened database successfully") createtable(conn) insertdata(conn) selectdata(conn) updatedata(conn) deletedata(conn) conn.close() 3.按照实际集群信息,修改pythondws.py文件中的集群公网访问地址、集群端口号、数据库名称、数据库用户名、数据库密码。 psycopg2接口不提供重试连接的能力,您需要在业务代码中实现重试处理。 conn psycopg2.connect(host'10.154.70.231', port'8000', database'gaussdb', 需要连接的database user'dbadmin', password'password') 数据库用户密码 4.执行以下命令,使用psycopg第三方库连接集群。 python pythondws.py 在Windows环境使用psycopg2第三方库连接集群 1.在Windows系统中,单击“开始”按钮 ,在搜索框中,键入 cmd ,然后在结果列表中单击“cmd.exe”打开命令提示符窗口。 2.在命令提示符窗口中,执行以下命令创建pythondws.py文件。 type nul> pythondws.py 请复制粘贴以下内容放入pythondws.py文件中: 请复制粘贴以下内容放入pythondws.py文件中: !/usr/bin/python coding:UTF8 from future import printfunction import psycopg2 def createtable(connection): print("Begin to create table") try: cursor connection.cursor() cursor.execute("drop table if exists test;" "create table test(id int, name text);") connection.commit() except psycopg2.ProgrammingError as e: print(e) else: print("Table created successfully") cursor.close() def insertdata(connection): print("Begin to insert data") try: cursor connection.cursor() cursor.execute("insert into test values(1,'number1');") cursor.execute("insert into test values(2,'number2');") cursor.execute("insert into test values(3,'number3');") connection.commit() except psycopg2.ProgrammingError as e: print(e) else: print("Insert data successfully") cursor.close() def updatedata(connection): print("Begin to update data") try: cursor connection.cursor() cursor.execute("update test set name 'numberupdated' where id1;") connection.commit() print("Total number of rows updated :", cursor.rowcount) cursor.execute("select from test order by 1;") rows cursor.fetchall() for row in rows: print("id ", row[0]) print("name ", row[1], "n") except psycopg2.ProgrammingError as e: print(e) else: print("After Update, Operation done successfully") def deletedata(connection): print("Begin to delete data") try: cursor connection.cursor() cursor.execute("delete from test where id3;") connection.commit() print("Total number of rows deleted :", cursor.rowcount) cursor.execute("select from test order by 1;") rows cursor.fetchall() for row in rows: print("id ", row[0]) print("name ", row[1], "n") except psycopg2.ProgrammingError as e: print(e) else: print("After Delete,Operation done successfully") def selectdata(connection): print("Begin to select data") try: cursor connection.cursor() cursor.execute("select from test order by 1;") rows cursor.fetchall() for row in rows: print("id ", row[0]) print("name ", row[1], "n") except psycopg2.ProgrammingError as e: print(e) print("select failed") else: print("Operation done successfully") cursor.close() if name 'main': try: conn psycopg2.connect(host'10.154.70.231', port'8000', database'postgresgaussdb',