使用Python第三方库psycopg2连接集群 在Linux环境使用psycopg2第三方库连接集群 1.以root用户登录Linux环境。 2.执行以下命令创建pythondws.py文件。 vi 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'gaussdb',