简体   繁体   English

如何将变量插入Sqlite3数据库

[英]how to insert variables into Sqlite3 database

I'm not familiar with SQL(or python to be honest), and i was wondering how to add variables into tables. 我不熟悉SQL(或者说是python),我想知道如何将变量添加到表中。 This is what i tried: 这是我尝试的:

import sqlite3
conn = sqlite3.connect('TESTDB.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS table(number real, txt text)''')
r=4
c.execute('''INSERT INTO table(r,'hello')''')
conn.commit()
conn.close()

This doesn't work.I get the error, "TypeError: 'str' object is not callable"How do i make the table insert the variable r?? 这不起作用。我收到错误消息:“ TypeError:'str'对象不可调用”如何使表插入变量r?

Thanks 谢谢

You have to bind values to placeholders in a prepared statement. 您必须在准备好的语句中将值绑定到占位符 See examples in the documentation . 请参阅文档中的示例。

Trying to build a query string on the fly with unknown values inserted directly in it is a great way to get a SQL injection attack and should be avoided. 尝试动态构建带有直接插入未知值的查询字符串是获得SQL注入攻击的好方法,应该避免。

Your problem is that you don't inject r properly into your query. 您的问题是您没有将r正确插入查询中。 This should work: 这应该工作:

c.execute('''INSERT INTO table(''' + str(r) + ''','hello')''')

cheers 干杯

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

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