python postgresql跨数据库操作_python操作postgreSQL数据库

本文介绍了一个Python脚本,用于将账单详情插入到开发数据库中。脚本使用‘awslambda - psycopg2’库连接PostgreSQL数据库,在开发的EC2实例上测试运行良好。下一步计划将脚本适配AWS Lambda并打包成zip包。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Coded a python script (as attached) for insert the biller details to the dev db, it works well per my testing on the dev ec2 instance (xxx-util-services). It use the "awslambda-psycopg2" library to for the Postgres connection.

https://github.com/jkehler/awslambda-psycopg2

Next step is to make the script to be a AWS lambda compatiable (with Lambda function handlers) and then package with the library into a AWS Lambda zip package.

#!/usr/bin/python

importpsycopg2from datetime importdatetime

db_host= "xxxxxx-esb-xx.xxxxx.xx-xxxx.rds.xxxxx.com"db_port= 5432db_name= "xxx"db_user= "xxx"db_pass= "xxxx"db_table= "xxxxx"biller_code= "111111"biller_short_name= "test_short"biller_long_name= "test_long"

defmake_conn():

conn=Nonetry:

conn= psycopg2.connect("dbname=‘%s‘ user=‘%s‘ host=‘%s‘ password=‘%s‘" %(db_name, db_user, db_host, db_pass))print "connected to postgres db successfully"

except:print "I am unable to connect to the database"

returnconntry:

connection=make_conn()

cursor=connection.cursor()

cursor.execute("SELECT * FROM billers where biller_code = ‘%s‘;" %biller_code)

numOfRows=cursor.rowcountprint("%s rows found for the biller code: %s" %(numOfRows, biller_code))if(numOfRows<=0):

dt=datetime.now()

cursor.execute("insert into billers (biller_code, biller_short_name, biller_long_name, active, min_length, max_length, reg_exp, check_digit_algo, created_at, updated_at) values (%s, %s, %s, true, 0, 100, ‘NONE‘, ‘NONE‘, %s, %s)", (biller_code, biller_short_name, biller_long_name, dt, dt))

connection.commit()print("inserted %s rows successfully" %cursor.rowcount)except(Exception, psycopg2.Error) as error :print ("Error caught", error)finally:#closing database connection.

if(connection):

cursor.close()

connection.close()print("PostgreSQL connection is closed")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值