# -*- coding: utf-8 -*-#
#-------------------------------------------------------------------------------
# Name: forum01
# Description:
# Author: Negoowen
# Date: 2020/2/2
__Author__ = 'Negoo_wen'
#-------------------------------------------------------------------------------
import psycopg2
import pprint
def connect_db():
try:
conn = psycopg2.connect(database='Test1', user='postgres',
password='root', host='127.0.0.1', port=5432)
except Exception as e:
print e
else:
return conn
return None
def close_db_connection(conn):
conn.commit()
conn.close()
def main():
conn = connect_db()
cur = conn.cursor()
node_id = []
sql_str_1 = "select node_id from public.addressbook01 where text=" + "\'"+ title + "\'"
cur.execute(sql_str_1)
rows = cur.fetchall()
close_db_connection(conn)
if len(rows)==0:
print "[!] 帖子id不存在!"
exit()
title_id = rows[0][0]
node_id.append(title_id)
print '[+] 此文章的id为: '+str(title_id)
for i in node_id:
conn = connect_db()
cur = conn.cursor()
sql_str_2 = "select node_id from public.addressbook01 where parent_id=" + str(i)
cur.execute(sql_str_2)
rows = cur.fetchall()
close_db_connection(conn)
for row in rows:
if row[0] not in node_id:
node_id.append(row[0])
print "[*] 子id为: "+ str(node_id)
print "[*] 子id长度为: : "+ str(len(node_id))
for nid in node_id:
conn = connect_db()
cur = conn.cursor()
sql_str_3 = 'SELECT text,node_id,parent_id FROM public.addressbook01 where node_id=' + str(nid)
cur.execute(sql_str_3)
rows = cur.fetchall()
close_db_connection(conn)
print '[+] text: %s node_id: %d parent_id: %d' %(rows[0])
if __name__ == '__main__':
title = raw_input('title:')
main()
使用python操作PostgreSQL层序遍历
最新推荐文章于 2024-08-23 14:54:20 发布