1

this is the code I would like to have, where I do not have to exactly specify the howtodothis variable during database creation. I want it to be dynamic instead.

class DbHandler():
    def __init__(self, howtodothis):
        self.database = sqlite3.connect('api_data.db')
        self.cursor = self.database.cursor()
        self.cursor.execute("CREATE TABLE IF NOT EXISTS ? (test)",(howtodothis,))

    def insert(self):
        self.cursor.execute("INSERT INTO ? VALUES (?)",(howtodothis,))

I now have this, but I wonder if it is safe

class DbHandler():
    def __init__(self, thisworks):
        self.database = sqlite3.connect('api_data.db')
        self.cursor = self.database.cursor()
        self.cursor.execute(f"CREATE TABLE IF NOT EXISTS {thisworks} (test)")

    def insert(self):
        self.cursor.execute(f"INSERT INTO {thisworks} VALUES (?)")

1 Answer 1

1

If thisworks is supplied by the user, there is a risk of being random SQL injections or characters that are not legal as SQLite identifiers in there.

Generally in relational design, adding tables or columns for specific user input is a bit frowned up. Usually a better design is to use a single table, and just have a column that holds the variable thisworks. Because in the end, select test from {thisworks} is about the same as select test from userdata where label = ?, param = {thisworks}, but way safer regarding injections and there's no risk of your database blowing up due to containing a bazillion tables. That being said, SQLite specifically supports 2 billion tables in one file, so you might get away with it.

If you do it, make sure to filter the supplied variable, best with a whitelist like only allowing a-z.

Sign up to request clarification or add additional context in comments.

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.