Home > Database > Mysql Tutorial > How Can I Execute SQL Queries from an External File in Python?

How Can I Execute SQL Queries from an External File in Python?

Linda Hamilton
Release: 2025-01-03 15:24:43
Original
458 people have browsed it

How Can I Execute SQL Queries from an External File in Python?

Running SQL Queries from an External File in Python

In Python, executing SQL queries is a versatile task. This article focuses on reading an external SQL file and executing the queries within.

The Issue: Executing Queries from a File

When executing specific queries from a file, it's not immediately clear how to tailor the c.execute() function to fetch query results. The provided code executes commands successfully but requires clarification for the line:

result = c.execute("SELECT * FROM %s;" % table);
Copy after login

Understanding String Formatting

The key to understanding this line is string formatting in Python. %s functions as a placeholder, and the following variable table replaces it. For example:

a = "Hi, my name is %s and I have a %s hat" % ("Azeirah", "cool")
print(a)
# Output: Hi, my name is Azeirah and I have a Cool hat
Copy after login

Applying String Formatting to Queries

By substituting %s with the table variable, the c.execute() function executes queries dynamically. The for loop iterates through tables, allowing sequential query execution.

The following code provides a reusable function for executing SQL scripts from files:

def executeScriptsFromFile(filename):
    fd = open(filename, 'r')
    sqlFile = fd.read()
    fd.close()
    
    sqlCommands = sqlFile.split(';')
    for command in sqlCommands:
        try:
            c.execute(command)
        except OperationalError, msg:
            print("Command skipped: ", msg)
Copy after login

To use it, simply call:

executeScriptsFromFile('zookeeper.sql')
Copy after login

With the power of string formatting, executing SQL queries from an external file in Python becomes a straightforward process, enabling dynamic query execution and efficient database manipulation.

The above is the detailed content of How Can I Execute SQL Queries from an External File in Python?. For more information, please follow other related articles on the PHP Chinese website!

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