⊗pyPmDBONO 105 of 128 menu

Printing a Single Record in Python

If you need to get only one record from the table, then outputting it through a loop makes the code redundant. To solve this problem, you need to use the fetchone method:

query = "SELECT * FROM users WHERE id=2" with connection.cursor(dictionary=True) as cursor: cursor.execute(query) result = cursor.fetchone() print(result)

After running the code, only one entry will be displayed:

{'id': 2, 'name': 'user2', 'age': 25, 'salary': 500}

Now let's set a condition in the query that matches multiple records:

query = "SELECT * FROM users WHERE salary>500" with connection.cursor(dictionary=True) as cursor: cursor.execute(query) result = cursor.fetchone() print(result)

In this case, only the first record that matches the specified conditions will be displayed:

{'id': 4, 'name': 'user4', 'age': 30, 'salary': 900}

Select one user who is over 25 years old.

Select one user whose age is less than 30 years and whose salary is more than 500.

byenru