【问题标题】:sqlite3.OperationalError... what is wrong in my sqlite syntax?sqlite3.OperationalError ...我的sqlite语法有什么问题?
【发布时间】:2015-12-22 10:35:45
【问题描述】:

Python 3 + tkinter 和 sqlite3

我正在做一个模拟应用程序来在 sqlite 中保存一段文本

功能如下:

 def saveNote(self,note_id):

    conn = db.connect(fname)
    c = conn.cursor()
    safeTitle=self.newNoteTitle.get()
    safeContents=self.newNoteText.get("1.0",tk.END)
    safeLink=self.newNoteLink.get()
    safeRemarks=self.newNoteRemarks.get()
    conn.execute('UPDATE notes SET (title,contents,remarks,link,created,last_modified,notebook_id) VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, ?) WHERE notes_id=5', (safeTitle, safeContents, safeRemarks, safeLink, 1))
    conn.commit()
        self.master.destroy()

在执行函数时,我得到这个错误:

 conn.execute('UPDATE notes SET (title,contents,remarks,link,created,last_modified,notebook_id) VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, ?) WHERE notes_id=5', (safeTitle, safeContents, safeRemarks, safeLink, 1))
sqlite3.OperationalError: near "(": syntax error

我不太明白为什么语法错误...(我是 python 新手)...谁能帮我找出错误?

谢谢

【问题讨论】:

标签: python sqlite tkinter


【解决方案1】:

我认为您的 SQL 语句不正确。根据您的解释,您希望将数据插入表中,因此您希望实际使用 INSERT 语句而不是 UPDATE。我想你可能想这样做:

INSERT INTO notes(title,contents,remarks,link,created,last_modified,notebook_id)
VALUES(INSERT_THE_VALUES_YOU_WANT_TO_INSERT_HERE)

如果您实际上是在寻找更新现有数据,那么您的语法应该如下所示:

只需在"" 中填写您要设置的值

UPDATE notes
SET 
title = "",
contents = "",
remarkts = "",
link = "",
created = "",
last_modified = "",
notebook_id = ""
WHERE notes_id=5

为了消除与我提供的查询的任何混淆,您希望在 Python 中像这样构造您的查询:

conn.execute('UPDATE notes SET title=?,contents=?,remarks=?,link=?,created=?,last_modified=?,notebook_id=?
WHERE notes_id=5', (safeTitle, safeContents, safeRemarks, safeLink, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, 1)) 

【讨论】:

  • 我实际上是在更新一个已经存在的笔记..因此为什么“硬编码”note_id(我试图调试它)
  • 那么你的更新语法不正确。我会更新我的答案。
  • 在这种情况下,我不会使用参数,将我的代码暴露给 sql 注入!
  • 我不知道你为什么要跳到 sql 注入。您正在尝试连接到数据库。您编写了不正确的 SQL 语法,并且为您提供了正确的语法。如果您担心 SQL 注入,那么您应该编写数据清理方法来检查每个输入。
  • 我的意思是......你的版本当然是正确的,但它是“不同的”,因为它不使用任何参数。据我了解,最佳实践是参数化查询以使其默认安全。另外,我想了解为什么该参数化语法是错误的,而不是使用替代方法......我从这里得到的参数:#example 1 -- simple placeholders db.execute('update player set name=?, score= ?, active=? where jerseyNum=?', ('Smith, Steve', 42, True, 99))
猜你喜欢
  • 2020-10-17
  • 2023-01-10
  • 1970-01-01
  • 2021-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-03
相关资源
最近更新 更多