我正在學習如何在python中執行SQL(我知道SQL,而不是Python)。在Python中讀取外部SQL腳本
我有一個外部的sql文件。它創建並將數據插入到三個表'Zookeeper','Handles','Animal'中。
然後我有一系列的查詢來運行表格。以下查詢位於我加載到python腳本頂部的zookeeper.sql文件中。例如,對於前兩個是:
--1.1
SELECT ANAME,zookeepid
FROM ANIMAL, HANDLES
WHERE AID=ANIMALID;
--1.2
SELECT ZNAME, SUM(TIMETOFEED)
FROM ZOOKEEPER, ANIMAL, HANDLES
WHERE AID=ANIMALID AND ZOOKEEPID=ZID
GROUP BY zookeeper.zname;
這些都在SQL執行罰款。現在我需要在Python中執行它們。我已經提供並完成了代碼來讀取文件。然後執行循環中的所有查詢。
1.1和1.2是我感到困惑的地方。我相信在這個循環中,我應該放置一些東西來運行第一個和第二個查詢。
result = c.execute(「SELECT * FROM%s;」%table);
但是什麼?我想我錯過了一些非常明顯的東西。我認爲扔掉我的是%表。在查詢1.1和1.2中,我不是創建表,而是查找查詢結果。
我的整個python代碼如下。
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
# For each of the 3 tables, query the database and print the contents
for table in ['ZooKeeper', 'Animal', 'Handles']:
**# Plug in the name of the table into SELECT * query
result = c.execute("SELECT * FROM %s;" % table);**
# Get all rows.
rows = result.fetchall();
# \n represents an end-of-line
print "\n--- TABLE ", table, "\n"
# This will print the name of the columns, padding each name up
# to 22 characters. Note that comma at the end prevents new lines
for desc in result.description:
print desc[0].rjust(22, ' '),
# End the line with column names
print ""
for row in rows:
for value in row:
# Print each value, padding it up with ' ' to 22 characters on the right
print str(value).rjust(22, ' '),
# End the values from the row
print ""
c.close()
conn.close()
你應該執行什麼SQL查詢,1.1和1.2,或者只是從每個表中獲取所有內容? – Azeirah
我想從.sql文件運行1.1和1.2(加上我有大約6個人)。 – mpg
我的速度有點過快我相信,您需要幫助瞭解代碼,還是需要編輯代碼來幫助您做些額外的事情? – Azeirah