简体   繁体   中英

Error in creating an SQLite database using the Python subprocess module

The following Python code tries to create an SQLite database and a table, using the command line in Linux:

#!/usr/bin/python2.6
import subprocess

args = ["sqlite3", "db.sqlite", "'CREATE TABLE my_table(my_column TEXT)'"]
print(" ".join(args))

subprocess.call(args)

When I ran the code, it created a database with zero bytes and the following output:

sqlite3 db.sqlite 'CREATE TABLE my_table(my_column TEXT)'
Error: near "'CREATE TABLE my_table(my_column TEXT)'": syntax error

But when I copied the command printed by the code (just above the error message), and pasted the command onto the command line, the command created a database with a table.

What is wrong with the code?

Besides the extra quoting that @Dirk mentions before, you can also create the database without spawning a subprocess:

import sqlite3

cnx = sqlite3.connect("e:/temp/db.sqlite")
cnx.execute("CREATE TABLE my_table(my_column TEXT)")
cnx.commit()
cnx.close()

Drop the ' in the second argument to sqlite (third element of the args list). The subprocess module does the quoting on its own and ensures, that the arguments gets passed to the executable as one string. It works on the command line, because there, the ' are necessary to tell the shell, that it should treat the enclosed string as single entity.

args = ["sqlite3", "db.sqlite", "CREATE TABLE my_table(my_column TEXT)"]

should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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