Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use with statement with MySQLdb.Connection object?

I wonder if I can use the context manager with with the Connection object, and write code like this:

with MySQLdb.connect(...) as conn:
    do_something()

Will the conn object be closed automatically after the block like with a file object ?

Thanks.

like image 907
Derrick Zhang Avatar asked Aug 01 '12 02:08

Derrick Zhang


People also ask

Which object is used to execute an SQL query in MySQLdb in Python?

Next, db object is used to create a cursor object, which in turn is used to execute SQL queries.

What are the arguments of MySQL _ connect () function?

connect() supports the following arguments: host , user , password , database , port , unix_socket , client_flags , ssl_ca , ssl_cert , ssl_key , ssl_verify_cert , compress .

What is MySQLdb cursors DictCursor?

In Python mysqldb I could declare a cursor as a dictionary cursor like this: cursor = db.cursor(MySQLdb.cursors.DictCursor) This would enable me to reference columns in the cursor loop by name like this: for row in cursor: # Using the cursor as iterator city = row["city"] state = row["state"]


1 Answers

MySQLdb does not support the context manager protocol. Roll your own, or use oursql instead.

like image 197
Ignacio Vazquez-Abrams Avatar answered Oct 31 '22 20:10

Ignacio Vazquez-Abrams