Help us understand the problem. What is going on with this article?

MySQLdbの優雅な使い方

More than 5 years have passed since last update.

共通部分

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)で自動エスケープ

fukkyy
Gunosyの中の人
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした