2013-10-20 23 views
18

私はPythonでSQLを実行する方法を学習しています(私はPythonではなくSQLを知っています)。Pythonで外部SQLスクリプトを読む

私は外部のsqlファイルを持っています。 'Zookeeper'、 'Handles'、 'Animal'の3つのテーブルにデータを作成して挿入します。

次に、テーブルを実行するための一連のクエリがあります。以下のクエリは、私がpythonスクリプトの先頭にロードするzookeeper.sqlファイルにあります。最初の2のための例は以下のとおりです。

--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が混乱しています。私はループの中で、最初と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') 

あなたはPythonでは

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

で混乱したと述べた使用します。

%sの文字列"Some string with %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 

ビットが、それは明確にする必要があります:プレースホルダを置き換えるには、あなたは、ex(「あなたがそれを交換したいもの」)あなたの文字列の後

%を追加します。今

、何

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

ああ、正式な "殴打"がないので、あなたは私を突き刺した。 Pythonがどのように動作するのかよく知っていることをお勧めします。あなたが問題を一つ一つ解決することはできません(私が行っても、次にできないことをしたいとき)。 [このウェブサイト](http://www.codecademy.com/)は、Pythonの基本的な構文を理解するのに役立ちます。 – Azeirah

+1

非常に役に立ちます。間違いなく私は将来の参照のために保存されます! python 3 ... – memilanuk

関連する問題