from mysql.connector import MySQLConnection, Error,connect db_username='root' db_password='root' database_name='testdb' db_host='127.0.0.1' def read_file(filename): with open(filename, 'rb') as f: photo = f.read() return photo def write_file(data, filename): with open(filename, 'wb') as f: f.write(data) def write_blob(author_id, filename): # read file data = read_file(filename) # prepare update query and data query = "INSERT INTO `images` (`id`,`photo`) VALUES (%s,%s)" args = (author_id,data) try: cnx = MySQLConnection(user=db_username, password=db_password, host=db_host, port='8889', \ unix_socket='/Applications/MAMP/tmp/mysql/mysql.sock', database=database_name) cursor = cnx.cursor() cursor.execute(query, args) cnx.commit() except Exception as e: print(e) finally: cursor.close() cnx.close() def update_blob(author_id, filename): # read file data = read_file(filename) # prepare update query and data query = "UPDATE images " \ "SET photo = %s " \ "WHERE id = %s" args = (data, author_id) try: cnx = MySQLConnection(user=db_username, password=db_password, host=db_host, port='8889', \ unix_socket='/Applications/MAMP/tmp/mysql/mysql.sock', database=database_name) cursor = cnx.cursor() cursor.execute(query, args) cnx.commit() except Exception as e: print(e) finally: cursor.close() cnx.close() def read_blob(author_id, filename): # select photo column of a specific author query = "SELECT photo FROM images WHERE id = %s" try: cnx = MySQLConnection(user=db_username, password=db_password, host=db_host, port='8889', \ unix_socket='/Applications/MAMP/tmp/mysql/mysql.sock', database=database_name) cursor = cnx.cursor() cursor.execute(query, (author_id,)) photo=cursor.fetchone()[0] # write blob data into a file write_file(photo, filename) except Exception as e: print(e) finally: cursor.close() cnx.close() def main(): write_blob(1,"whyno.jpg") update_blob(1, "svg_map.jpg") read_blob(1,"02.jpg") if __name__ == '__main__': main()