首页 >数据库 >mysql教程 >如何在 Python 中从外部脚本执行 SQL 查询并处理特定于表的查询?

如何在 Python 中从外部脚本执行 SQL 查询并处理特定于表的查询?

Mary-Kate Olsen
Mary-Kate Olsen原创
2024-12-30 03:54:08407浏览

How Can I Execute SQL Queries from an External Script in Python and Handle Table-Specific Queries?

在 Python 中从外部脚本执行 SQL 查询

使用 Python 和 SQL 时,通常会遇到需要执行存储在外部脚本中的 SQL 查询的情况。这个过程包括读取脚本,将其分解为单独的查询,然后逐个执行它们。

提供的代码

import sqlite3
from sqlite3 import OperationalError

conn = sqlite3.connect('csc455_HW3.db')
c = conn.cursor()

# Open and read the file as a single buffer
fd = open('ZooDatabase.sql', 'r')
sqlFile = fd.read()
fd.close()

# all SQL commands (split on ';')
sqlCommands = sqlFile.split(';')

# Execute every command from the input file
for command in sqlCommands:
    # This will skip and report errors
    # For example, if the tables do not yet exist, this will skip over
    # the DROP TABLE commands
    try:
        c.execute(command)
    except OperationalError, msg:
        print "Command skipped: ", msg

此代码有效地将 SQL 脚本读取为字符串,拆分将其分解为单独的命令,并使用 c.execute() 执行它们。但是,提供的代码片段中的其余代码不完整,需要修改以处理特定于表的查询。

执行特定于表的查询

代码缺少执行表的步骤-具体查询。为此,您可以修改代码如下:

for table in ['ZooKeeper', 'Animal', 'Handles']:
    result = c.execute("SELECT ANAME,zookeepid FROM ANIMAL, HANDLES WHERE AID=ANIMALID;")
    rows = result.fetchall()
    print("\n--- TABLE", table, "\n")

    for desc in result.description:
        print(desc[0].rjust(22, ' '), end=", ")  # Print column names

    print()

    for row in rows:
        for value in row:
            print(str(value).rjust(22, ' '), end=", ")  # Print each value
        print()

此代码将循环遍历表名称并为每个表执行指定的查询。然后,它格式化并打印表详细信息、列名称和行数据。

以上是如何在 Python 中从外部脚本执行 SQL 查询并处理特定于表的查询?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn