Guest User

Untitled

a guest
Dec 9th, 2018
721
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.03 KB | None | 0 0
  1. import mysql.connector
  2.  
  3. db_username='mehdi'
  4. db_password='mehdi'
  5. database_name='cra_db'
  6. db_host='127.0.0.1'
  7.  
  8. def read_file(filename):
  9. with open(filename, 'rb') as f:
  10. photo = f.read()
  11. return photo
  12.  
  13. def write_file(data, filename):
  14. with open(filename, 'wb') as f:
  15. f.write(data)
  16.  
  17. def write_blob(author_id, filename):
  18. # read file
  19. data = read_file(filename)
  20. # prepare update query and data
  21. query = "INSERT INTO `cra_db`.`authors` (`id`,`photo`) VALUES(%s,%s)"
  22. args = (author_id,data)
  23. try:
  24. cnx = mysql.connector.connect(user=db_username, password=db_password, host=db_host, database=database_name)
  25. cursor = cnx.cursor()
  26. cursor.execute(query, args)
  27. cnx.commit()
  28. except Exception as e:
  29. print(e)
  30. finally:
  31. cursor.close()
  32. cnx.close()
  33.  
  34. def update_blob(author_id, filename):
  35. # read file
  36. data = read_file(filename)
  37. # prepare update query and data
  38. query = "UPDATE authors "
  39. "SET photo = %s "
  40. "WHERE id = %s"
  41. args = (data, author_id)
  42. try:
  43. cnx = mysql.connector.connect(user=db_username, password=db_password, host=db_host, database=database_name)
  44. cursor = cnx.cursor()
  45. cursor.execute(query, args)
  46. cnx.commit()
  47. except Exception as e:
  48. print(e)
  49. finally:
  50. cursor.close()
  51. cnx.close()
  52.  
  53. def read_blob(author_id, filename):
  54. # select photo column of a specific author
  55. query = "SELECT photo FROM authors WHERE id = {}".format(author_id)
  56. try:
  57. cnx = mysql.connector.connect(user=db_username, password=db_password, host=db_host, database=database_name)
  58. cursor = cnx.cursor()
  59. cursor.execute(query)
  60. out=cursor.fetchall()
  61. # write blob data into a file
  62. write_file(out, filename)
  63. except Exception as e:
  64. print(e)
  65. finally:
  66. cursor.close()
  67. cnx.close()
  68.  
  69. def main():
  70. write_blob(15,"01.jpg")
  71. update_blob(144, "01.jpg")
  72. read_blob(144,"02.jpg")
  73.  
  74. if __name__ == '__main__':
  75. main()
Add Comment
Please, Sign In to add comment