📜  如何在Python中打印出 MySQL 表的所有行?

📅  最后修改于: 2022-05-13 01:54:36.983000             🧑  作者: Mango

如何在Python中打印出 MySQL 表的所有行?

MySQL 服务器是一个开源的关系数据库管理系统,是对基于 Web 的应用程序的主要支持。数据库和相关表格是许多网站和应用程序的主要组成部分,因为数据是通过网络存储和交换的。为了从 Web 服务器(此处为 XAMPP)访问 MySQL 数据库,我们使用Python中的各种模块,例如 PyMySQL、mysql.connector 等。

在本文中,我们将看到如何通过在Python和 MySQL 之间建立数据库连接来获取 MySQL 表的所有行。

首先,我们将连接到具有 MySQL 表的数据库。用于获取所有行的 SQL 查询:

SELECT * FROM table-name 

最后,获取所有行后,使用迭代器显示表中的每一行。

下面是一些描述如何从数据库中的 MySQL 表中提取行的程序:

示例 1:

下面是表geeksdemo是数据库极客,它将被Python脚本访问:

下面是获取 MYSQL 表中所有行的程序:

Python3
# import required modules
import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
  
# connect python with mysql with your hostname, 
# username, password and database
db= MySQLdb.connect("localhost", "root", "", "GEEK")
  
# get cursor object
cursor= db.cursor()
  
# execute your query
cursor.execute("SELECT * FROM geeksdemo")
  
# fetch all the matching rows 
result = cursor.fetchall()
  
# loop through the rows
for row in result:
    print(row)
    print("\n")


Python3
# import required modules
import MySQLdb
import pymysql
pymysql.install_as_MySQLdb()
  
# connect python with mysql with your hostname,
# username, password and database
db = MySQLdb.connect("localhost", "root", "", "techgeeks")
  
# get cursor object
cursor = db.cursor()
  
# execute your query
cursor.execute("SELECT * FROM techcompanies")
  
# fetch all the matching rows
result = cursor.fetchall()
  
# loop through the rows
for row in result:
    print(row, '\n')


输出:

示例 2:

这是从给定数据库中的表中提取所有行的另一个示例,以下是表方案和行:

下面是从表中提取所有每一行的Python脚本:

蟒蛇3

# import required modules
import MySQLdb
import pymysql
pymysql.install_as_MySQLdb()
  
# connect python with mysql with your hostname,
# username, password and database
db = MySQLdb.connect("localhost", "root", "", "techgeeks")
  
# get cursor object
cursor = db.cursor()
  
# execute your query
cursor.execute("SELECT * FROM techcompanies")
  
# fetch all the matching rows
result = cursor.fetchall()
  
# loop through the rows
for row in result:
    print(row, '\n')

输出: