Home >Backend Development >Python Tutorial >How to Create Dynamic Tables in SQLite Safely?
In database management, flexibility and efficiency are paramount. When working with SQLite, the question arises: can variable table names be used without resorting to string constructors, a practice susceptible to SQL injection attacks?
In this case, the goal is to create a table for each star in a star simulation. Each table should be named according to the star's name. Initially, the approach involves using string constructors:
cursor.execute("CREATE TABLE StarFrame"+self.name+" (etc etc)")
However, this is not ideal. To address the issue, one may consider using parameters:
cursor.execute("CREATE TABLE StarFrame(?) (etc etc)",self.name)
Unfortunately, tables cannot be the target of parameter substitution. Hence, this approach is not feasible.
Instead, to ensure protection against injection attacks, a sanitization function can be employed. This function filters out special characters and ensures the table name contains only alphanumeric characters:
def scrub(table_name): return ''.join( chr for chr in table_name if chr.isalnum() ) table_name = scrub(self.name) cursor.execute(f"CREATE TABLE StarFrame{table_name} (etc etc)")
This approach allows for dynamic table creation while safeguarding against security threats. By stripping out potential injection vectors, it maintains database integrity and prevents malicious actors from exploiting the application.
The above is the detailed content of How to Create Dynamic Tables in SQLite Safely?. For more information, please follow other related articles on the PHP Chinese website!