Python 및 SQL로 작업할 때 외부 스크립트에 저장된 SQL 쿼리를 실행해야 하는 경우가 흔합니다. 이 프로세스에는 스크립트를 읽고 이를 개별 쿼리로 나누고 하나씩 실행하는 작업이 포함됩니다.
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()를 사용하여 실행합니다. 그러나 제공된 스니펫의 나머지 코드는 불완전하며 테이블별 쿼리를 처리하려면 수정해야 합니다.
코드에 테이블을 실행하는 단계가 없습니다. - 특정 쿼리. 이렇게 하려면 다음과 같이 코드를 수정하면 됩니다.
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 중국어 웹사이트의 기타 관련 기사를 참조하세요!