1

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?

1
  • We should also say: Python has a built in module to handle sqlite: docs.python.org/library/sqlite3.html That's likely to be much cleaner than calling a separate process to do it. Commented Feb 10, 2011 at 17:57

2 Answers 2

3

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()
Sign up to request clarification or add additional context in comments.

1 Comment

You might want to note that SQLite creates a database if you attempt to connect to one that does not exist.
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.