
Python の外部スクリプトから SQL クエリを実行する
Python と SQL を使用する場合、外部スクリプトに格納されている SQL クエリを実行する必要が生じることがよくあります。このプロセスには、スクリプトの読み取り、個々のクエリへの分割、およびそれらのクエリの 1 つずつの実行が含まれます。
提供されたコード
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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
|
ログイン後にコピー
このコードは、SQL スクリプトを効率的に文字列に読み取り、分割します。それを個々のコマンドに分割し、c.execute() を使用して実行します。ただし、提供されたスニペットの残りのコードは不完全であるため、テーブル固有のクエリを処理するように変更する必要があります。
テーブル固有のクエリの実行
コードにはテーブルを実行するステップがありません。 - 特定のクエリ。これを行うには、コードを次のように変更します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | for table in [ 'ZooKeeper' , 'Animal' , 'Handles' ]:
result = c.execute( "SELECT ANAME,zookeepid FROM ANIMAL, HANDLES WHERE AID=ANIMALID;" )
rows = result.fetchall()
print ( "\n--- TABLE" , table, "\n" )
for desc in result.description:
print (desc[0].rjust(22, ' ' ), end = ", " ) # Print column names
print ()
for row in rows:
for value in row:
print (str(value).rjust(22, ' ' ), end = ", " ) # Print each value
print ()
|
ログイン後にコピー
このコードはテーブル名をループし、テーブルごとに指定されたクエリを実行します。次に、テーブルの詳細、列名、行データをフォーマットして出力します。
以上がPython の外部スクリプトから SQL クエリを実行し、テーブル固有のクエリを処理するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。