Я работаю над тем, как выполнять SQL в python (я знаю SQL, а не Python).
У меня есть внешний sql файл. Он создает и вставляет данные в три таблицы: "Zookeeper", "Handles", "Animal".
Затем у меня есть серия запросов для запуска таблиц. Нижеприведенные запросы находятся в файле zookeeper.sql, который я загружаю в верхней части python script. Пример для первых двух:
--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);
но что? Я думаю, что мне не хватает чего-то очень очевидного. Я думаю, что меня выбрасывает% 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()