在python中读取外部sql脚本

mpg*_*mpg 44 python sql

我正在学习如何在python中执行SQL(我知道SQL,而不是Python).

我有一个外部的sql文件.它创建数据并将数据插入三个表'Zookeeper','Handles','Animal'.

然后我有一系列查询来运行表.以下查询位于我在python脚本顶部加载的zookeeper.sql文件中.前两个示例是:

--1.1

SELECT ANAME,zookeepid
FROM ANIMAL, HANDLES
WHERE AID=ANIMALID;
Run Code Online (Sandbox Code Playgroud)

--1.2

SELECT ZNAME, SUM(TIMETOFEED)
FROM ZOOKEEPER, ANIMAL, HANDLES
WHERE AID=ANIMALID AND ZOOKEEPID=ZID
GROUP BY zookeeper.zname;
Run Code Online (Sandbox Code Playgroud)

这些都在SQL中执行得很好.现在我需要在Python中执行它们.我已经给出并完成了在文件中读取的代码.然后执行循环中的所有查询.

1.1和1.2是我感到困惑的地方.我相信循环这是我应该放置的东西来运行第一个和第二个查询.

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

但什么?我想我错过了一些非常明显的东西.我认为让我失望的是%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()
Run Code Online (Sandbox Code Playgroud)

Aze*_*rah 87

您的代码已经包含了一种从指定的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
Run Code Online (Sandbox Code Playgroud)

将其包装在一个函数中,您可以重用它.

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
Run Code Online (Sandbox Code Playgroud)

使用它

executeScriptsFromFile('zookeeper.sql')
Run Code Online (Sandbox Code Playgroud)

你说你很困惑

result = c.execute("SELECT * FROM %s;" % table);
Run Code Online (Sandbox Code Playgroud)

在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
Run Code Online (Sandbox Code Playgroud)

有点幼稚的例子,但应该很清楚.

怎么办

result = c.execute("SELECT * FROM %s;" % table);
Run Code Online (Sandbox Code Playgroud)

意味着,它是否用表变量的值替换%s.

(创建于)

for table in ['ZooKeeper', 'Animal', 'Handles']:


# for loop example

for fruit in ["apple", "pear", "orange"]:
    print fruit
>>> apple
>>> pear
>>> orange
Run Code Online (Sandbox Code Playgroud)

如果您有任何其他问题,请戳我.

  • 此代码将尝试对所有 sql 文档执行空字符串查询。尾随分号将创建一个空字符串列表元素。尝试: sqlCommands = filter(None, sqlFile.split(';')) (3认同)
  • @Azeirah 您的回答可能会导致 SQL 注入,您可以让它使用 `?` 语法进行 SQL 格式设置吗? (3认同)
  • 这一直有效,直到您的 SQL 文件中有一个包含“;”的文本列 (2认同)
  • @ TrevorJ.Smith直接在StackOverflow上发布的所有代码都是根据知识共享许可证获得许可的[更多信息请参阅此帖子](https://meta.stackexchange.com/questions/12527/do-i-have-to-worry-约 - 版权问题换码张贴上堆栈溢出).我不是律师,如果您认为在您的案件中可能有必要,请咨询律师. (2认同)

小智 9

在python中将外部脚本读入sqlite数据库的一种非常简单的方法是使用executescript()

import sqlite3

conn = sqlite3.connect('csc455_HW3.db')

with open('ZooDatabase.sql', 'r') as sql_file:
    conn.executescript(sql_file.read())

conn.close()
Run Code Online (Sandbox Code Playgroud)