简体   繁体   English

如何从python中执行SQLite脚本?

[英]How do I execute an SQLite script from within python?

My SQLite script works fine, when I type: 当我键入以下内容时,我的SQLite脚本可以正常工作:

.read 'dummy.sql' .read'dummy.sql'

from within the SQLite shell. 在SQLite Shell中。

However, the following Python code is not doing it properly. 但是,以下Python代码无法正确执行。 I'm getting a syntax error in line 5. 我在第5行中收到语法错误。

import sqlite3
db = sqlite3.connect('scheduling.db')
cursor=db.cursor()
a='''.read "scheduling.sql"'''
cursor.execute(a)
db.commit
db.close()

I know I'm doing something wrong with the quotes. 我知道引号做错了。 How do I make this work? 我该如何工作?

You cannot. 你不能。 The program sqlite3 can be seen as splitted in 2 parts: 程序sqlite3可以分为两部分:

  • externally, it parses lines of input into SQL commands 在外部,它将输入行解析为SQL命令
  • internally, it passes those SQL commands to the engine 在内部,它将那些SQL命令传递给引擎
  • externally again, it displays the result of the SQL commands. 再次在外部显示SQL命令的结果。

.read is kind of a meta command: the parser opens the file and read lines from it. .read是一种meta命令:解析器打开文件并从中读取行。 AFAIK, nothing in the sqlite3 library can emulate that parser part, so you would have to the line parsing into SQL statements by hand , and then execute the SQL statements one at a time. AFAIK,sqlite3库中没有任何东西可以模拟该解析器部分,因此您必须手动将行解析为SQL语句,然后一次执行一个SQL语句。

Try this. 尝试这个。 you can read query from file using the 'open' function - this will replace 您可以使用“打开”功能从文件中读取查询-这将替换

.read 。读

functionality; 功能; SQL scripts are text files with query. SQL脚本是带有查询的文本文件。 and then run read_sql_query. 然后运行read_sql_query。

import sqlite3
import pandas as pd
sqlite_file = 'scheduling.db'
conn = sqlite3.connect(sqlite_file)
c = conn.cursor()
f = open('scheduling.sql','r')
sql = f.read() 
print pd.read_sql_query(sql, conn)

The workaround I would recommend is to read the contents of the .sql file into a Python string variable, as you would read any other text file, and then call executescript . 我建议的解决方法是像读取其他任何文本文件一样,将.sql文件的内容读取到Python字符串变量中,然后调用executescript Unlike execute , executescript can execute many statements in one call. execute不同, executescript可以在一个调用中执行许多语句。 For example, it will work correctly if your .sql contains the following: 例如,如果您的.sql包含以下内容,它将可以正常工作:

CREATE TABLE contacts (
 contact_id INTEGER PRIMARY KEY,
 first_name TEXT NOT NULL,
 last_name TEXT NOT NULL
);

INSERT INTO contacts (contact_id, first_name, last_name)
VALUES (1, 'John', 'Smith');

Here's the full Python snippet that you'll need: 这是您需要的完整Python代码段:

import sqlite3

with open('scheduling.sql', 'r') as sql_file:
    sql_script = sql_file.read()

db = sqlite3.connect('scheduling.db')
cursor = db.cursor()
cursor.executescript(sql_script)
db.commit()
db.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM