sqlite3变量形式传入表名(table name) python

其实就是字符串拼接,目前没找到别的方法。

方法1

def data_entry(table_name,arg1,arg2,arg3,arg4):
    c.execute('insert into '+table_name+' values(:sex,:name,:age,:job)',  {"sex":arg1,"name":arg2,"age":arg3,"job":arg4})

方法2

def data_entry(table_name,arg1,arg2,arg3,arg4):

    c.execute('insert into '+table_name+' values(?,?,?,?)',(arg1,arg2,arg3,arg4))

 

而且sqlite3不按照相应字段设置的数据类型填入值也完全没有问题。

但记住最后一定要commit(),这才是写入数据库的关键,没这步直接关闭数据库的话一切数据库操作就白费了!!!

 

以下摘自sqlite3官方文档以供参考,https://docs.python.org/3/library/sqlite3.html#sqlite3.Cursor.execute

 

Usually your SQL operations will need to use values from Python variables. You shouldn’t assemble your query using Python’s string operations because doing so is insecure; it makes your program vulnerable to an SQL injection attack (see https://xkcd.com/327/ for humorous example of what can go wrong).

Instead, use the DB-API’s parameter substitution. Put ? as a placeholder wherever you want to use a value, and then provide a tuple of values as the second argument to the cursor’s execute() method. (Other database modules may use a different placeholder, such as %s or :1.) For example:

# Never do this -- insecure!
symbol = 'RHAT'
c.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol)

# Do this instead
t = ('RHAT',)
c.execute('SELECT * FROM stocks WHERE symbol=?', t)
print(c.fetchone())

# Larger example that inserts many records at a time
purchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
             ('2006-04-05', 'BUY', 'MSFT', 1000, 72.00),
             ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
            ]
c.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases)
上一篇:关于Uncaught TypeError: nt.setState.bind is not a function报错解决


下一篇:比较器整理