python读取json文件存取pgsql数据库
1、首先要下载安装psycopg2包
2.建库建表
create table testdb
(
int id,
text json
);
3.读取现有的json文件
def readfile(rpath): with open(rpath, 'r') as load_f: load_dict = json.load(load_f) return load_dict
4、存入pgsql数据库中,
rpath=”D:\\123.json”
conn = psycopg2.connect(database="testdb", user="postgres", password="123456", host="127.0.0.1", port="5432") print "Opened database successfully" cur = conn.cursor() data = readfile(rpath) json_str = json.dumps(data) json_str = "'" + json_str + "'" insert_query = "INSERT INTO testj(id,textstr) VALUES (111," + json_str + ")" cur.execute(insert_query) conn.commit() conn.close()
5读取
sql="select textstr from testj where id =111;" cur = conn.cursor() cur.execute(sql) rows = cur.fetchall() print type(rows[0]) lines=rows[0][0]
ok大功告成!