2013-10-20 7 views
18

Ich arbeite an einem lernen, wie man SQL in Python ausführen (ich kenne SQL, nicht Python).Lesen von externen SQL-Skript in Python

Ich habe eine externe SQL-Datei. Es erstellt und fügt Daten in drei Tabellen "Zookeeper", "Handles", "Animal" ein.

Dann habe ich eine Reihe von Abfragen von den Tabellen ablaufen. Die folgenden Abfragen befinden sich in der zoekeeper.sql-Datei, die ich am Anfang des Python-Skripts einlade. Beispiel für die ersten beiden sind:

--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; 

Diese alle ausführen fein in SQL. Jetzt muss ich sie in Python ausführen. Ich habe Code erhalten und vervollständigt, um die Datei einzulesen. Führen Sie anschließend alle Abfragen in der Schleife aus.

Die 1.1 und 1.2 ist, wo ich verwirrt bin. Ich glaube an die Schleife, das ist die Zeile, wo ich etwas einfügen sollte, um die erste und dann zweite Abfrage auszuführen.

Ergebnis = c.execute ("SELECT * FROM% s;"% Tabelle);

aber was? Ich denke, ich vermisse etwas sehr Offensichtliches. Ich denke, was mich abwirft ist% Tabelle. In Abfrage 1.1 und 1.2 erstelle ich keine Tabelle, sondern suche nach einem Abfrageergebnis.

Mein gesamter Python-Code ist unten.

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() 
+0

Welche SQL-Abfrage (n) sollen Sie ausführen, die 1.1 und 1.2, oder einfach alles aus jeder Tabelle holen? – Azeirah

+0

Ich möchte 1.1 und 1.2 (plus ich habe etwa 6 andere) aus der .SQL-Datei ausführen. – mpg

+0

Ich gehe ein bisschen zu schnell Ich glaube, brauchst du Hilfe, um den Code zu verstehen, oder brauchst du Hilfe beim Bearbeiten deines Codes, um etwas extra zu tun? – Azeirah

Antwort

46

Ihr Code enthält bereits eine schöne Art und Weise alle Anweisungen von einer bestimmten SQL-Datei

# 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 

Wrap dies in einer Funktion auszuführen, und Sie können es wieder verwenden.

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 

Um es zu nutzen

executeScriptsFromFile('zookeeper.sql') 

Sie sagten, Sie von

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

In Python verwechselt wurden, man Sachen in einen String von etwas namens String Formatierung hinzufügen können.

Sie haben eine Zeichenfolge "Some string with %s" mit% s, das ist ein Platzhalter für etwas anderes. Um den Platzhalter zu ersetzen, fügen Sie% („was Sie es mit ersetzen wollen“), nachdem die Zeichenfolge

ex:

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 

Bit eines kindischen Beispiel, aber es sollte klar sein.

Nun, was

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

Mittel sind es% s mit dem Wert des Tabellenvariable ersetzt.

(erstellt in)

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


# for loop example 

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

Wenn Sie weitere Fragen haben, stoßen mich.

+1

Freut mich, meine Fragen offline zu stellen, aber wie stochern Sie auf SOF? Ich habe eingesteckt, wovon ich denke, dass du darüber gesprochen hast, und eine Reihe von Fehlern bekommen. Ich bekomme immer noch nichts. MPG – mpg

+0

Oh, es gibt kein offizielles "Stochern" in SO, in meinen Worten hast du mich nur gestochen. Ich denke, es ist das Beste für Sie, sich mit der Funktionsweise von Python vertraut zu machen, da ich nicht alle Ihre Probleme einzeln beheben kann (selbst wenn ich das nächste Mal etwas tun möchte, was Sie nicht können). [Diese Website] (http://www.codecademy.com/) wird Ihnen auf jeden Fall helfen, die grundlegende Syntax von Python zu verstehen. – Azeirah

+1

Sehr hilfreich; definitiv etwas, das ich für zukünftige Referenz sparen werde! A [geringfügige zwicken] (http://pastebin.com/Wy884qCJ) mit Python 3 zu arbeiten ... – memilanuk