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

博客介绍了字符串拼接在sqlite3操作中的情况,指出sqlite3不按字段数据类型填值也可行。强调写入数据库时最后要执行commit(),否则操作白费,还给出sqlite3官方文档参考,提醒避免用Python字符串操作组装查询以防SQL注入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

方法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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值