Чтобы запустить сценарий SQL с использованием Python, существует несколько способов. Вот несколько примеров:
Метод 1: использование модуля sqlite3(для баз данных SQLite)
import sqlite3
# Connect to the SQLite database
conn = sqlite3.connect('database.db')
# Open the SQL script file
with open('script.sql', 'r') as file:
script = file.read()
# Execute the script
conn.executescript(script)
# Commit the changes
conn.commit()
# Close the connection
conn.close()
Метод 2: использование модуля psycopg2(для баз данных PostgreSQL)
import psycopg2
# Connect to the PostgreSQL database
conn = psycopg2.connect(
host='localhost',
database='dbname',
user='username',
password='password'
)
# Open the SQL script file
with open('script.sql', 'r') as file:
script = file.read()
# Create a cursor object
cursor = conn.cursor()
# Execute the script
cursor.execute(script)
# Commit the changes
conn.commit()
# Close the cursor and connection
cursor.close()
conn.close()
Метод 3: использование модуля mysql.connector(для баз данных MySQL)
import mysql.connector
# Connect to the MySQL database
conn = mysql.connector.connect(
host='localhost',
database='dbname',
user='username',
password='password'
)
# Open the SQL script file
with open('script.sql', 'r') as file:
script = file.read()
# Create a cursor object
cursor = conn.cursor()
# Execute the script
cursor.execute(script, multi=True)
# Commit the changes
conn.commit()
# Close the cursor and connection
cursor.close()
conn.close()
Это всего лишь несколько примеров запуска сценариев SQL на Python. Конкретный метод, который вы выберете, будет зависеть от типа используемой базы данных. Не забудьте заменить 'database.db', 'script.sql', 'localhost', 'dbname', 'username'и 'password'с соответствующими значениями для вашей настройки.