Sending Database Queries in Python
After connecting to the database, you can send queries to it. This is done using the variable query
, in which an SQL query is written to display all data from the table users
. This variable should be written in the block with the variable connection
:
try:
with connect(
host='localhost',
user='root',
password='',
database='test',
) as connection:
query = "SELECT * FROM users"
except Error as e:
print(e)
Next, we write another with
construction to work with the MySQLConnection object stored in the connection
variable. Special methods must be applied to this object sequentially. The first of them is the cursor
method, which creates a CMySQLCursor object from the MySQLConnection object. The execute
method is applied to it in turn, which ensures the execution of the SQL query passed to it as a parameter:
try:
with connect(
...
) as connection:
query = "SELECT * FROM users"
with connection.cursor() as cursor:
cursor.execute(query)
Next, you need to extract all the data using the fetchall
method and write it to the result
variable. And to output the obtained data, you need to pass it through the for
loop:
try:
with connect(
...
) as connection:
query = "SELECT * FROM users"
with connection.cursor() as cursor:
cursor.execute(query)
result = cursor.fetchall()
for row in result:
print(row)
The full code will look like this:
try:
with connect(
host='localhost',
user='root',
password='',
database='test',
) as connection:
query = "SELECT * FROM users"
with connection.cursor() as cursor:
print(cursor)
cursor.execute(query)
result = cursor.fetchall()
for row in result:
print(row)
except Error as e:
print(e)
After executing the code, all records will be output to the console as tuples:
(1, 'user1', 23, 400)
(2, 'user2', 25, 500)
(3, 'user3', 23, 500)
(4, 'user4', 30, 900)
(5, 'user5', 27, 500)
(6, 'user6', 28, 900)
Display all data from the users
table.