Python SQL SELECT 语句

在本节中,我们将向您解释如何在 Python 编程语言中编写 SQL SELECT 语句。以及如何从表中提取或选择记录。 

在开始 SELECT 示例之前,请访问 图表数据 文章,了解我们将使用的数据。

Python SQL SELECT 语句 示例

在此示例中,我们将展示如何使用 SELECT 语句表中 选择记录。请参阅 连接服务器 文章,了解在 Python 中建立连接的步骤。以下是我们可以对 SQL Server 执行的一些操作,但不仅限于这些。

  1. 创建数据库
  2. 选择排序后的表记录
  3. 前 10 条记录
  4. Where 子句
# Example
import pyodbc
conn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
                      "Server=PRASAD;"
                      "Database=SQL Tutorial;"
                      "Trusted_Connection=yes;")

cursor = conn.cursor()
cursor.execute('SELECT * FROM CustomerSale')

for row in cursor:
    print('row = %r' % (row,))
Select Statement Example

首先,我们从 Tutorial 数据库中的 Customer Sales 表导入或选择了数据。

cursor = cursor.execute('SELECT * FROM CustomerSale')

接下来,我们使用 For 循环 迭代 Customer Sales 表中的每一行。在 For 循环中,我们使用 print 语句打印行。

for row in cursor:
    print('row = %r' % (row,))

Python SQL SELECT 语句 示例 2

您无需选择所有不必要的列(使用 * ),而是可以根据需要选择所需的列。此示例从 Customer Sales 表中选择 Employee Id、Occupation、Yearly Income 和 Sales 列。

# Example
import pyodbc
conn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
                      "Server=PRASAD;"
                      "Database=SQL Tutorial;"
                      "Trusted_Connection=yes;")

cursor = conn.cursor()
cursor.execute('SELECT EmpID, Occupation, YearlyIncome, Sales FROM CustomerSale')

for row in cursor:
    print('row = %r' % (row,))
Select Example 3

选择数据库记录 示例 3

游标有许多函数。您可以使用这些游标函数来修改 select 语句提供的结果。要查看游标函数类型,请在游标后输入 .,IDLE 会显示所有可用的函数。

例如,Python fetchone 函数仅从 中获取一行或一条记录。

# Example
import pyodbc
conn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
                      "Server=PRASAD;"
                      "Database=SQL Tutorial;"
                      "Trusted_Connection=yes;")

cursor = conn.cursor()
cursor.execute('SELECT * FROM CustomerSale')
result = cursor.fetchone()
print(result)
Cursor Example