您的位置:首页 > 编程语言 > Python开发

Python操作postgreSQL 实例

2015-09-09 21:21 483 查看
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