MySQL provides a variety of methods to read data in the database. This article will focus on the two most commonly used methods:
The SELECT statement is the most commonly used method for reading from a database. It is used to extract data from one or more tables. The general syntax of a SELECT statement is as follows:
<code>SELECT <列名> FROM <表名> [WHERE <条件>] [GROUP BY <列名>] [HAVING <条件>] [ORDER BY <列名>] [LIMIT <行数>]</code>
Example:
Select all customers' names and emails from the customers
table:
<code class="sql">SELECT name, email FROM customers;</code>
fetchall()
method is another way to read data when interacting with MySQL using Python. fetchall()
The method stores all result rows in a list of tuples, each tuple representing a row of data.
Example:
Use Python's mysql.connector
library to read the names and values of all customers from the customers
table Email:
<code class="python">import mysql.connector # 建立数据库连接 connection = mysql.connector.connect( host='localhost', user='root', password='', database='database_name' ) # 创建游标对象 cursor = connection.cursor() # 执行查询 cursor.execute("SELECT name, email FROM customers") # 存储结果 result = cursor.fetchall() # 遍历结果 for name, email in result: print(f'{name} - {email}') # 关闭游标和连接 cursor.close() connection.close()</code>
The above is the detailed content of How to read database data in mysql. For more information, please follow other related articles on the PHP Chinese website!