Подтвердить что ты не робот

Чтение внешнего sql script в python

Я работаю над тем, как выполнять 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()
4b9b3361

Ответ 1

В вашем коде уже есть прекрасный способ выполнить все инструкции из указанного SQL файла

# 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

Оберните это в функцию, и вы можете его повторно использовать.

def executeScriptsFromFile(filename):
    # Open and read the file as a single buffer
    fd = open(filename, '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

Чтобы использовать его

executeScriptsFromFile('zookeeper.sql')

Вы сказали, что вас смутили

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

В Python вы можете добавить материал в строку, используя что-то, называемое форматированием строки.

У вас есть строка "Some string with %s" с% s, которая содержит место для чего-то другого. Чтобы заменить местозаполнитель, вы добавите% ( "что вы хотите заменить" ) после строки

Пример:

a = "Hi, my name is %s and I have a %s hat" % ("Azeirah", "cool")
print(a)
>>> Hi, my name is Azeirah and I have a Cool hat

Немного детского примера, но это должно быть ясно.

Теперь, что

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

означает, что он заменяет% s значением переменной таблицы.

(создан)

for table in ['ZooKeeper', 'Animal', 'Handles']:


# for loop example

for fruit in ["apple", "pear", "orange"]:
    print fruit
>>> apple
>>> pear
>>> orange

Если у вас возникнут какие-то дополнительные вопросы, соберите меня.