pgsql_util.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. #!/usr/bin/python
  2. # -*- coding:utf-8 -*-
  3. import sys
  4. import os
  5. from pgdb import Connection
  6. import json
  7. sys.path.append(os.path.abspath('..'))
  8. from util.config import config
  9. def get_conn():
  10. conn = Connection(database=config.get('pgsql', 'db'), host=config.get('pgsql', 'host'),
  11. user=config.get('pgsql', 'user'), password=config.get('pgsql', 'password'))
  12. return conn
  13. def insert(sql):
  14. try:
  15. conn = get_conn()
  16. cur = conn.cursor()
  17. cur.execute(sql)
  18. conn.commit()
  19. except Exception as e:
  20. print(e)
  21. finally:
  22. cur.close()
  23. conn.close()
  24. def update(sql):
  25. try:
  26. conn = get_conn()
  27. conn.execute(sql)
  28. conn.commit()
  29. except Exception as e:
  30. print(e)
  31. finally:
  32. conn.close()
  33. def get_rows(sql):
  34. try:
  35. conn = get_conn()
  36. return conn.query(sql)
  37. except Exception as e:
  38. print(e)
  39. finally:
  40. conn.close()
  41. def get_total(sql):
  42. conn = None
  43. try:
  44. conn = get_conn()
  45. result = conn.query(sql)
  46. return int(result[0]['count'])
  47. except Exception as e:
  48. print(e)
  49. finally:
  50. conn.close()
  51. def demo():
  52. sql = "select aid,other_info FROM articles where aid = '5afa6e5a-9004-4182-a743-87d77c97b451'"
  53. rows = get_rows(sql)
  54. for row in rows:
  55. print(row)
  56. other_info = row['other_info']
  57. print(other_info)
  58. other_info_json = json.loads(other_info)
  59. print(other_info_json.get('abstract'))
  60. def demo1():
  61. sql = "select count(*) FROM articles"
  62. total = get_total(sql)
  63. print(total)
  64. PAGE_SIZE = 50
  65. def demo2(offset):
  66. sql = "select aid,other_info FROM articles order by aid LIMIT %s OFFSET %s"
  67. update_sql = '''
  68. UPDATE articles
  69. set other_info = %s
  70. WHERE aid = %s
  71. '''
  72. rows = get_rows(sql % (PAGE_SIZE, 0))
  73. conn = get_conn()
  74. for row in rows:
  75. aid = row['aid']
  76. other_info = json.loads(row['other_info'])
  77. if 'abstract' in other_info:
  78. del other_info['abstract']
  79. if 'notes' in other_info:
  80. del other_info['notes']
  81. if 'content' in other_info:
  82. del other_info['content']
  83. print(json.dumps(other_info), aid)
  84. conn.execute(update_sql, (json.dumps(other_info), aid))
  85. conn.close()
  86. def demo3():
  87. for i in range(0, 100, 50):
  88. demo2(i)
  89. if __name__ == "__main__":
  90. demo1()