LoginSignup
0
0

More than 1 year has passed since last update.

postされたファイル(画像やExcelファイル等)をDBに登録 Part2

Last updated at Posted at 2022-08-10

前回、MySQLdb.connectのcursorによる直書きSQLでエラーが発生し、
pandasを用いてファイルを丸ごと登録したわけだが(https://qiita.com/v4ns/items/98cf4bdc65d46b3f1764 ) 、
原因というか解決策が判明したので記載する。

代入を行う%sを使う場合は、パラメータをまとめる変数を介すること

解決策は、どうやらパラメータ用変数に投げてから%sでSQL文に当てはめることだった。その結果、エラーが出ずに実行できた。

qiita.py
             #現在時刻を取得
             time = datetime.datetime.now()
             # データベースへの接続とカーソルの生成
             connection = MySQLdb.connect(
                 host='localhost',
                 user='root',
                 passwd='passwd',
                 db='db')
             cursor = connection.cursor()
             sql = ('''update example set addresser = %s,file =  %s ,created = %s ,last_updated = %s where id = %s ''') 
             # ここに実行したいコードを入力します
             # 使うパラメータから順に変数に入れていく
             params = (str(request.form['name']),frame,str(time),str(time),str(request.form['id']))
             # SQL文にパラメータをいれて実行
             cursor.execute(sql,params)
             # 保存を実行
             connection.commit()
              
             # 接続を閉じる
             connection.close()

これでいけた。ありがとう、パラメータの人。
足りないimportはエラー表示を参考に適宜入れてください。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0