database_access.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. # -*- coding: utf-8 -*-
  2. import dataset
  3. import pandas as pd
  4. import pymysql
  5. def check_unique(table, value):
  6. #---if there is the same url, return 0---
  7. if len([i for i in table.find(url=value)]) > 0:
  8. return 0
  9. else:
  10. return 1
  11. def DBconnect():
  12. db = dataset.connect('sqlite:///gs.db')
  13. print('Have {} tables: {}'.format(len(db.tables), str(db.tables)))
  14. return db
  15. def Tabelconnect(db, table_name):
  16. table=db[table_name]
  17. print('Have {} columns: {}'.format(len(table.columns),str(table.columns)))
  18. return table
  19. def DataToCsv(table, output_file_name):
  20. db = dataset.connect('sqlite:///gs.db')
  21. table=db[table]
  22. data = pd.DataFrame([dict(i) for i in table])
  23. print('output data size: {}'.format(len(data)))
  24. data.to_csv(output_file_name, index=False)
  25. def mysql_connect(mysql_config, DB_name):
  26. # Open database connection
  27. db = pymysql.connect(
  28. host = mysql_config['MYSQL_HOST'],
  29. port = mysql_config['MYSQL_PORT'],
  30. user = mysql_config['MYSQL_USER'],
  31. password = mysql_config['MYSQL_PASSWORD'],
  32. db = DB_name,
  33. )
  34. return db
  35. def create_table(db, table_name, schema):
  36. cursor = db.cursor()
  37. # Drop table if it already exist using execute() method.
  38. cursor.execute("DROP TABLE IF EXISTS {}".format(table_name))
  39. cursor.execute(schema)
  40. print("Created table {} Successfull.".format(table_name))
  41. cursor.close()
  42. def mysql_data_version(db):
  43. # prepare a cursor object using cursor() method
  44. cursor = db.cursor()
  45. # execute SQL query using execute() method.
  46. cursor.execute("SELECT VERSION()")
  47. # Fetch a single row using fetchone() method.
  48. data = cursor.fetchone()
  49. print ("Database version : %s " % data)
  50. def mysql_insert_data(db, insert_sql):
  51. cursor = db.cursor()
  52. try:
  53. # Execute the SQL command
  54. cursor.execute(insert_sql)
  55. # Commit your changes in the database
  56. db.commit()
  57. except Exception as e:
  58. print(e)
  59. # Rollback in case there is any error
  60. db.rollback()
  61. cursor.close()
  62. def mysql_select_data(db, query_sql):
  63. cursor = db.cursor()
  64. # Prepare SQL query to select a record from the table.
  65. try:
  66. # Execute the SQL command
  67. cursor.execute(query_sql)
  68. # Fetch all the rows in a list of lists.
  69. results = cursor.fetchall()
  70. except:
  71. import traceback
  72. traceback.print_exc()
  73. print ("Error: unable to fetch data")
  74. return results