Python で MySQL の blob にデータを登録する方法のメモ。
■登録
■検索
■実行結果
■登録
import sys import requests import MySQLdb def main(): db = MySQLdb.connect( host='localhost', user='***', passwd='***', db='***' ) url = 'https://www.goo.ne.jp' resp = requests.get(url) sql = f"insert into test_blob1 set url = %(url)s, body = %(body)s" cursor = db.cursor() cursor.execute(sql, {'url': url, 'body': resp.content}) db.commit() cursor.close() db.close() return 0 if __name__ == '__main__': res = main() exit(res)
■検索
import sys import requests import MySQLdb def main(): db = MySQLdb.connect( host='localhost', user='***', passwd='***', db='***' ) url = 'https://www.goo.ne.jp' sql = f"select * from test_blob1" cursor = db.cursor() cursor.execute(sql) rows = cursor.fetchall() for row in rows: print(f"url: {row[0]}") print(f"body: {row[1].decode('utf-8')}") cursor.close() db.close() return 0 if __name__ == '__main__': res = main() exit(res)
■実行結果
url: https://www.goo.ne.jp body: <!DOCTYPE HTML> <html lang="ja"> <head> <meta charset="utf-8"> <meta name="referrer" content="unsafe-url"> <!--[if !IE]><meta http-equiv="X-UA-Compatible" content="IE=edge"><![endif]--> ...