0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

MySQLdb(mysqlclient) cursor.execute()でカラム名に変数を指定する

Last updated at Posted at 2020-07-12

環境

SQLサーバー

OS: Archlinux
SQL サーバー: mysql Ver 15.1 Distrib 10.4.13-MariaDB, for Linux (x86_64) using readline 5.1

クライアント

OS: Windows 10 build 1909
言語: Python 3.8.4rc1
SQLクライアント: mysqlclient 2.0.1

ハマったところ

このように書きたかった

hash_type = 'md5'
fpath = '/home/me/test.txt'
hash = '0123456789ABCDEF0123456789ABCDEF'

connection = MySQLdb.connect(......)
cursor = connection.cursor()
cursor.execute(
    'UPDATE hashes (path, %s) VALUE (%s, %s);',
    (hash_type, fpath, hash)
)

次のようなエラーが出る

MySQL Error [1064]: You have an error in your SQL syntax; ...(略)...

このときのSQL文は

UPDATE hashes (path, 'hash_type') VALUE ('fpath', 'hash');

原因

カラム名に引用符''が含まれているから

解決

次のように引用符を取り除いたSQL文を与える

UPDATE hashes (path, hash_type) VALUE ('fpath', 'hash');

execute()の引数ではなくSQL文にformat()を用いて文字列に置き換える

cursor.execute(
    'UPDATE hashes (path, {}) VALUE (%s, %s);'.foramt(hash_type),
    (fpath, hash)
)
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?