简体   繁体   English

由于字符串替换不利于形成 SQL 查询,您如何动态分配表名?

[英]Being that string substitution is frowned upon with forming SQL queries, how do you assign the table name dynamically?

Pretty new to sqlite3, so bear with me here.. sqlite3 还很新,所以请耐心等待..

I'd like to have a function to which I can pass the table name, and the values to update.我想要一个函数,我可以向它传递表名和要更新的值。

I initially started with something like this:我最初从这样的事情开始:

def add_to_table(table_name, string):
    cursor.execute('INSERT INTO {table} VALUES ({var})'
        .format(
            table=table_name,
            var=string)
        )

Which works A-OK, but further reading about sqlite3 suggested that this was a terribly insecure way to go about things.这行得通,但进一步阅读 sqlite3 表明这是一种非常不安全的处理方式。 However, using their ?但是,使用他们的? syntax, I'm unable to pass in a name to specify the variable.语法,我无法传递名称来指定变量。

I tried adding in a ?我尝试添加一个? in place of the table, but that throws a syntax error.代替表,但这会引发语法错误。

cursor.execute('INSERT INTO ? VALUES (?)', ('mytable','"Jello, world!"'))
>> >sqlite3.OperationalError: near "?": syntax error  

Can the table in an sql statement be passed in safely and dynamically? sql语句中的table可以安全动态传入吗?

Its not the dynamic string substitution per-se thats the problem.这不是动态字符串替换本身的问题。 Its dynamic string substitution with an user-supplied string thats the big problem because that opens you to SQL-injection attacks.它使用用户提供的字符串进行动态字符串替换,这是一个大问题,因为这会让您面临 SQL 注入攻击。 If you are absolutely 100% sure that the tablename is a safe string that you control then splicing it into the SQL query will be safe.如果您绝对 100% 确定 tablename 是您控制的安全字符串,那么将其拼接到 SQL 查询中将是安全的。

if some_condition():
   table_name = 'TABLE_A'
else:
   table_name = 'TABLE_B'

cursor.execute('INSERT INTO '+ table_name + 'VALUES (?)', values)

That said, using dynamic SQL like that is certainly a code smell so you should double check to see if you can find a simpler alternative without the dynamically generated SQL strings.也就是说,使用这样的动态 SQL 肯定是一种代码味道,因此您应该仔细检查是否可以找到更简单的替代方案,而无需动态生成的 SQL 字符串。 Additionally, if you really want dynamic SQL then something like SQLAlchemy might be useful to guarantee that the SQL you generate is well formed.此外,如果您真的想要动态 SQL,那么像 SQLAlchemy 这样的东西可能有助于保证您生成的 SQL 格式正确。

Composing SQL statements using string manipulation is odd not only because of security implications, but also because strings are "dumb" objects.使用字符串操作编写 SQL 语句很奇怪,不仅因为安全隐患,还因为字符串是“哑”对象。 Using sqlalchemy core (you don't even need the ORM part) is almost like using strings, but each fragment will be a lot smarter and allow for easier composition.使用 sqlalchemy 核心(您甚至不需要 ORM 部分)几乎就像使用字符串一样,但每个片段都会更加智能,并且可以更轻松地组合。 Take a look at the sqlalchemy wiki to get a notion of what I'm talking about.查看sqlalchemy wiki以了解我在说什么。

For example, using sqlsoup your code would look like this:例如,使用 sqlsoup 您的代码将如下所示:

db = SQLSoup('sqlite://yourdatabase')
table = getattr(db, tablename)
table.insert(fieldname='value', otherfield=123)
db.commit()

Another advantage: code is database independent - want to move to oracle?另一个优势:代码独立于数据库——想迁移到 oracle? Change the connection string and you are done.更改连接字符串,您就完成了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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