python外部脚本_在python中读取外部sql脚本

我正在研究如何在python中执行SQL(我知道SQL,而不是Python)。

我有一个外部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是我感到困惑的地方。 我相信在循环中这是我应该放置一些内容来运行第一个然后第二个查询的行。

结果= 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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值