Python操作postgreSQL 实例

psycopg2下载网址:http://www.stickpeople.com/projects/python/win-psycopg/


连接的代码实例:
import psycopg2 as ps


def connect_sql():
    #create database
    conn = ps.connect (database="ammeter", user="postgres", password="postgres",
                     port="5432", host="127.0.0.1")
    cur = conn.cursor()


    #create table
    cur.execute("""create table if not exists test_table1
        (user_number CHAR(20) NOT NULL,
         user_type CHAR(20) ,
         meter_point_name TEXT,
         asset_number CHAR(30) ,
         factory_number CHAR(20),
         display_type CHAR(20),
         last_display CHAR(20),
         current_display CHAR(20),
         comprehensive_rate CHAR(20),
         last_power CHAR(20),
         current_power CHAR(20),
         status CHAR(20) ,
         abnormal_assort TEXT ,
         data_from TEXT,
         user_address TEXT);""")
    conn.commit()
#insert record
command_head="insert into test_table values("
for record in self.record_arr:
strs=""
for segment in record:
strs=strs+"'"+str(segment)+"',"
strs=strs[:-1]
command=command_head+strs+");"
cur.execute(command)
conn.commit()

conn.close()

你可能感兴趣的:(Python操作postgreSQL 实例)