[PYTHON] Graceful use of MySQLdb

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

Graceful use of MySQLdb
Convenient use of ipython
Use and integration of "Shodan"
Let's use usercustomize.py instead of sitecustomize.py
Summary of how to use pandas.DataFrame.loc
Let's use tomotopy instead of gensim
Proper use of Python visualization packages
Make full use of Python's str.format
[Python Queue] Convenient use of Deque
Survey for practical use of BlockChain
Efficient use of Linux file system
Summary of how to use csvkit
[Python] Summary of how to use pandas
Use of constraints file added in pip 7.1
How to calculate Use% of df command
[Python2.7] Summary of how to use unittest
R: Use Japanese instead of Japanese in scripts
Use Django's Markdownx outside of site root
Jupyter Notebook Basics of how to use
List of Atom packages I really use
Basics of PyTorch (1) -How to use Tensor-
Summary of how to use Python list
[Python2.7] Summary of how to use subprocess
[Question] How to use plot_surface of python