且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

python sqlite问题-插入方法

更新时间:2023-12-01 13:03:16

insert_query = '''INSERT INTO testTable ({0}) VALUES ({1})'''.format(
               (','.join(listOfVars)), ','.join('?'*len(listOfVars)))
cur.executemany(insert_query, tupleForm)

请不要对数据库查询使用普通的字符串插值.
我们很幸运有 DB-API 详细解释了如何做你需要什么.

Please do not use normal string interpolation for database queries.
We are fortunate to have the DB-API which explains in detail how to do what you require.


这种方法比第二次尝试更好的几个简单原因:


A couple of quick reasons why this method is better than your 2nd attempt:

  1. 通过使用内置的字符串转义工具,我们可以避免 SQL 注入攻击,并且
  2. executemany 接受元组列表作为参数.
  1. by using the built-in string-escaping tools we avoid SQL injection attacks, and
  2. executemany accepts a list of tuples as an argument.