common part
import MySQLdb
args = {"hostname": "poko",
"db": "hoge",
"user": "pokopoko",
"passwd": "hogehoge",
"charset": "utf-8"
}
Ungraceful writing
con = MySQLdb.connect(**args)
cur = con.cursor()
#Processing that requires 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()
Elegant writing
Use with
and cur.execute (query, args)
with MySQLdb.connect(**args) as cur:
cur.execute("INSERT INTO pokos (id, poko_name) VALUES (%s, %s)", (id, poko_name))
It doesn't get messed up with the writing style below.
You can also prevent forgetting to commit or opening a connection. Rollback if an exception occurs.
In with, the return value of __enter__ ()
is entered after as.
__exit () __
is called when exiting the with block
Automatic escape with cur.execute (query, args)
Recommended Posts