2013-10-20 66 views
18

我正在學習如何在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() 
+0

你應該執行什麼SQL查詢,1.1和1.2,或者只是從每個表中獲取所有內容? – Azeirah

+0

我想從.sql文件運行1.1和1.2(加上我有大約6個人)。 – mpg

+0

我的速度有點過快我相信,您需要幫助瞭解代碼,還是需要編輯代碼來幫助您做些額外的事情? – Azeirah

回答

46

您的代碼已經包含了一個美麗的方式從指定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 

如果您有任何其他問題,捅我。

+1

很高興能夠在線下提出我的問題,但您如何嘲笑SOF?我插入了我認爲你在談論的內容,並且遇到了一些錯誤。所以我還沒有得到什麼。 MPG – mpg

+0

哦,在SO中沒有官方的「捅」,用我的話來說,你剛剛戳了我。我認爲你最好熟悉Python的整體工作方式,因爲我無法一個接一個地解決所有的問題(即使我這樣做,下一次你想做一些你不能做的事)。 [本網站](http://www.codecademy.com/)一定會幫助你理解python的基本語法。 – Azeirah

+1

非常有幫助;絕對是我將來保存以供將來參考的東西! [小調整](http://pastebin.com/Wy884qCJ)與python 3 ... – memilanuk