27
31

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 5 years have passed since last update.

MySQLdbの優雅な使い方

Last updated at Posted at 2013-08-09

共通部分

import MySQLdb

args = {"hostname": "poko",
		"db": "hoge",
		"user": "pokopoko",
		"passwd": "hogehoge",
		"charset": "utf-8"
		}

優雅でない書き方

con = MySQLdb.connect(**args)
cur = con.cursor()

# commitが必要な処理
cur.execute("INSERT INTO pokos (id, poko_name) VALUES (%s, %s)" % (con.literal(id), con.literal(poko_name)))
con.commit()

cur.close()
con.close()

優雅な書き方

withcur.execute(query, args)を利用

with MySQLdb.connect(**args) as cur:
	cur.execute("INSERT INTO pokos (id, poko_name) VALUES (%s, %s)", (id, poko_name))

下の書き方だとごちゃごちゃしない。
commit忘れやconnectionの開放の忘れなども防げる。例外が起きたらrollbackも。
withではas以降に__enter__()の返り値が入る。
withブロックを抜けるとき__exit()__がよばれる

cur.execute(query, args)で自動エスケープ

27
31
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
27
31

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?