db.execute('CREATE TABLE IF NOT EXISTS test (name TEXT)')
print("Table created successfully")
db.execute('INSERT INTO %s VALUES (%s)' % ('test', 'sample'))
db.close()
我正在使用Python。该表是使用“name”列成功创建的,但我无法插入任何内容。
我收到错误:
sqlite3.OperationalError: no such column: sample
为什么?
答案 0 :(得分:2)
我认为你需要这样的东西:
event.pathParameters
翻译成python:
INSERT INTO test (name)
VALUES
('sample');
答案 1 :(得分:1)
您忘记了列名?
db.execute('CREATE TABLE IF NOT EXISTS test (name TEXT)')
print("Table created successfully")
db.execute('INSERT INTO %s (name) VALUES (%s)' % ('test', 'sample'))
db.close()
答案 2 :(得分:0)
您需要提交更改。如果您不调用db.commit()
,则在关闭数据库时将回滚您的更改(包括创建表)。
答案 3 :(得分:-1)
这应该有效:
db.execute('INSERT INTO test VALUES (%s)' % ('sample'))
答案 4 :(得分:-1)
你绝对不想使用字符串替换。这会打开你https://www.owasp.org/index.php/SQL_Injection。相反,使用数据库绑定可以偶然修复您的实际错误(即您将sample
视为列名而不是数据)。
好的,不妨写下来:
import sqlite3
db = sqlite3.connect(':memory')
#you control this stuff, as the db schema isn't typically coming from user data
#so less likely to be a mess...
#i.e. build your query templates with string substitutions, but exec with binds.
tablename = 'test'
db.execute('CREATE TABLE IF NOT EXISTS %s (name TEXT)' % (tablename))
print("Table created successfully")
qry = 'INSERT INTO %s VALUES (?)' % (tablename)
#the data is where you want to be careful
db.execute(qry, ('sample',))
print ("insert done")
db.close()
给出:
Table created successfully
insert done
查看文档@ https://docs.python.org/2/library/sqlite3.html从开始#永不这样做 - 不安全!。