Advertisement
Guest User

Untitled

a guest
Aug 14th, 2017
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. import pymysql.cursors
  2. import os
  3. from attrdict import AttrDict
  4. import sys
  5.  
  6. # Test a one-row Insert, Select for Capacity DB
  7. # ... using Py DB-API
  8. #
  9. # Install:
  10. # pip3 install PyMySQL attrdict
  11. #
  12. # Refs:
  13. # PyMySQL pure-Py driver for MySQL - Python DB-API
  14. #
  15. # Run:
  16. # env DB_PASSWD=xyzzy1234 DB_HOST='10.10.100.101' DB=capacity DB_TABLE=capacity_openstack python3 -m pdb capacity_openstack/csv_summary_tosql.py # noqa
  17.  
  18. TEST_ENTRY = "compute,rackspace-dfw-dev,total_ram,380.0,500.0,0.76,120.0,2017-07-13 22:44:11.194554" # noqa: E501
  19.  
  20.  
  21. def main():
  22.  
  23. vals = TEST_ENTRY.split(',')
  24. print(vals, file=sys.stderr)
  25.  
  26. connobj = AttrDict(host=os.getenv('DB_HOST', 'localhost'),
  27. user=os.getenv('DB_USER', 'capacity'),
  28. password=os.getenv('DB_PASSWD', 'xyzzy'),
  29. db=os.getenv('DB', 'mydbname'),
  30. charset='utf8',
  31. cursorclass=pymysql.cursors.DictCursor,)
  32.  
  33. # connect to the Capacity database
  34. connobj.dbc = pymysql.connect(**connobj)
  35. connobj.db_table = os.getenv('DB_TABLE', 'my_db_table')
  36.  
  37. try:
  38. with connobj.dbc.cursor() as cursor:
  39. # Create a new Capacity record
  40. sql = """INSERT INTO {db_table}(cap_type, cloud_region,
  41. measurement, in_use, cap_limit, percent, remaining, utc_datetime)
  42. VALUES (%s, %s, %s, %s, %s, %s, %s, %s)""".\
  43. format(db_table=connobj.db_table)
  44.  
  45. cursor.execute(sql, vals)
  46.  
  47. # connection is NOT "autocommit by default; commit to save changes!
  48. connobj.dbc.commit()
  49.  
  50. with connobj.dbc.cursor() as cursor:
  51. # Read a single Capcity record
  52. sql = "SELECT * FROM {db_table}".format(db_table=connobj.db_table)
  53. cursor.execute(sql)
  54. result = cursor.fetchone()
  55. print(result, file=sys.stderr)
  56.  
  57. finally:
  58. connobj.dbc.close()
  59.  
  60.  
  61. if __name__ == '__main__':
  62. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement