ICode9

精准搜索请尝试: 精确搜索
首页 > 数据库> 文章详细

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

2019-05-22 22:48:16  阅读:510  来源: 互联网

标签:execute name python arg1 arg2 表名 sqlite3 table


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

方法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)

标签:execute,name,python,arg1,arg2,表名,sqlite3,table
来源: https://blog.csdn.net/amber_o0k/article/details/90452727

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有