All Courses

How can we retrieve data from an SQL database in Python and convert it into a list of strings instead of tuples?

By Pp5344229@gmail.com, a month ago
  • Bookmark
0

"What is the syntax to fetch data in Python from SQL as a list of strings instead of tuples?"

Sql
Python
1 Answer
0
Goutamp777

To retrieve data from an SQL database in Python and convert it into a list of strings instead of tuples, you can use the fetchall() method of the cursor object returned by the execute() method.


Assuming you have established a connection to the SQL database and have created a cursor object, here's an example of how to retrieve data and convert it to a list of strings:


# execute SQL query to retrieve data
cursor.execute("SELECT name, age FROM mytable")


# fetch all the rows as tuples
rows = cursor.fetchall()


# convert tuples to list of strings
rows = [list(map(str, row)) for row in rows]


# print the list
print(rows)

In the above code, fetchall() retrieves all the rows from the result set returned by the execute() method. Each row is returned as a tuple, with one element for each column in the result set.


The next line converts each tuple to a list of strings using the map() function and the str() function. The map() function applies the str() function to each element in the tuple, returning a new list of strings. The list() function then converts this new list into a regular Python list.


Finally, the list of lists is printed.

Your Answer

Webinars

Live Masterclass on : "How Machine Get Trained in Machine Learning?"

Mar 30th (7:00 PM) 516 Registered
More webinars

Related Discussions

Running random forest algorithm with one variable

View More