Using a context manager with mysql connector python

2024/10/9 2:26:01

I'm moving my code across from an sqlite database to mysql and I'm having a problem with the context manager, getting the following attribute error.

I've tried combinations of mydb.cursor() as cursor, mydb: etc...

mydb = mysql.connector.connect(host="localhost",user="root",passwd="",database="database_name"cur = mydb.cursor()
with mydb as cursor:AttributeError: __enter__
Answer

Python has a built-in way to implement a context manager if the object you're creating have a .close() method, by using the contextlib.closing context manager.

From the Python docs:

contextlib.closing(thing)

Return a context manager that closes thing upon completion of the block. This is basically equivalent to:

 from contextlib import contextmanager@contextmanagerdef closing(thing):try:yield thingfinally:thing.close()

So, for your specific issue, you can use not only on the connection, but also the cursor.

Your code would be:

from contextlib import closingimport mysql.connectorquery = "SELECT * FROM table"db_conn_info = {"user": "root","passwd": "","host": "localhost","port": 5000,"database": "database_name"
}with closing(mysql.connector.connect(**db_conn_info)) as conn:with closing(conn.cursor()) as cur:cur.execute(query)result = cur.fetchall()
https://en.xdnf.cn/q/70069.html

Related Q&A

Value of Py_None

It is clear to me that None is used to signify the lack of a value. But since everything must have an underlying value during implementation, Im looking to see what value has been used in order to sign…

Getting the href of a tag which is in li

How to get the href of the all the tag that is under the class "Subforum" in the given code?<li class="subforum"> <a href="Link1">Link1 Text</a> </l…

Put value at centre of bins for histogram

I have the following code to plot a histogram. The values in time_new are the hours when something occurred.time_new=[9, 23, 19, 9, 1, 2, 19, 5, 4, 20, 23, 10, 20, 5, 21, 17, 4, 13, 8, 13, 6, 19, 9, 1…

plot in Pandas immediately closes

I have a problem of plotting the data. I run the following python code:import pandas as pd df = pd.read_csv("table.csv")values = df["blah"] values.plot() print 1df[blahblah].plot() …

Django template: Embed css from file

Im working on an email template, therefor I would like to embed a css file<head><style>{{ embed css/TEST.css content here }}</style> </head>instead of linking it<head><…

handling async streaming request in grpc python

I am trying to understand how to handle a grpc api with bidirectional streaming (using the Python API).Say I have the following simple server definition:syntax = "proto3"; package simple;serv…

Add new column to a HuggingFace dataset

In the dataset I have 5000000 rows, I would like to add a column called embeddings to my dataset. dataset = dataset.add_column(embeddings, embeddings) The variable embeddings is a numpy memmap array of…

Django: how to order_by on a related field of a related field

Im using annotate to add a property to an object which I can then use for order_by. However, I want to annotate on a field of a relation on a relation. I know I should be able to get to the field someh…

How to extract the cell state and hidden state from an RNN model in tensorflow?

I am new to TensorFlow and have difficulties understanding the RNN module. I am trying to extract hidden/cell states from an LSTM. For my code, I am using the implementation from https://github.com/ay…

Python - Nested List to Tab Delimited File?

I have a nested list comprising ~30,000 sub-lists, each with three entries, e.g.,nested_list = [[x, y, z], [a, b, c]].I wish to create a function in order to output this data construct into a tab delim…