在Python 中讀取外部SQL 腳本
問題:如何從Python 腳本執行外部SQL 腳本中執行外部SQL 查詢,尤其是在處理非表創建時查詢?
說明:
要在 Python 中執行 SQL 指令,可以使用 sqlite3 模組。此模組提供了 SQLite 資料庫管理系統的介面。要讀取外部 SQL 腳本,可以按照以下步驟操作:
程式碼範例:
import sqlite3 # Open the database connection conn = sqlite3.connect('database.db') c = conn.cursor() # Read the SQL file with open('external_sql.sql', 'r') as f: sql_file = f.read() # Split the commands sql_commands = sql_file.split(';') # Execute the commands for command in sql_commands: try: c.execute(command) except sqlite3.OperationalError as e: print(f"Command skipped: {e}") # Commit the changes and close the connection conn.commit() c.close() conn.close()
特定查詢:
您提供的SQL 腳本中的查詢1.1 和1.2 是非建表查詢。要執行它們,您可以直接使用 c.execute 方法而不是 SELECT * 查詢:
# Query 1.1 result = c.execute( """ SELECT ANAME,zookeepid FROM ANIMAL, HANDLES WHERE AID=ANIMALID; """ ) # Get the results rows = result.fetchall() # Print the results print("Query 1.1:") for row in rows: print(row) # Query 1.2 result = c.execute( """ SELECT ZNAME, SUM(TIMETOFEED) FROM ZOOKEEPER, ANIMAL, HANDLES WHERE AID=ANIMALID AND ZOOKEEPID=ZID GROUP BY zookeeper.zname; """ ) # Get the results rows = result.fetchall() # Print the results print("Query 1.2:") for row in rows: print(row)
以上是如何在Python中執行外部SQL查詢(包括非建表查詢)?的詳細內容。更多資訊請關注PHP中文網其他相關文章!