Home > Database > Mysql Tutorial > body text

How to read database data in mysql

下次还敢
Release: 2024-04-14 18:36:34
Original
419 people have browsed it

MySQL reads database data

MySQL provides a variety of methods to read data in the database. This article will focus on the two most commonly used methods:

SELECT statement

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>
Copy after login

Example:

Select all customers' names and emails from the customers table:

<code class="sql">SELECT name, email
FROM customers;</code>
Copy after login

fetchall() method

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>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template