简体   繁体   中英

safe way to create sqlite3 table in python

For inserting into a table, the safe way is

c.execute("insert into table (?,?,?,...)",my_tuple)

But how does one create a table safely? I've tried something like this:

conn = sqlite3.connect(database)
c = conn.cursor()
cmd = "create table ? (? text,? text)"
my_tuple = ("my_table","first","second")
c.execute(cmd,my_tuple)

but I get errors like this:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
sqlite3.OperationalError: near "?": syntax error

Should I just assemble a string in python and throw it at sqlite to create the table?

This answer to a similar question might help https://stackoverflow.com/a/3247553/1709198

There the answerer thought it was not possible to name tables with the question mark method and instead proposed a way to 'sanitize' inputs by defining a function to 'scrub' the input which would remove things like )(][;, so that someone can't try to throw in sql code like ); drop tables -- ); drop tables -- to mess things up.

I also don't know of any way to make the question mark method work with table names and I think this 'sanitize the string' method is about as good as it gets.

If you're just trying to import csv files, and assuming that they're not being sent to you by some user who might try to mess with your database , just put it together in Python:

"create table %s (%s text,%s text)" % ("my_table","first","second")

If there's any chance the spreadsheets could come from a malicious user, then it's up to you to worry about sanitising the column / file names.

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