【问题标题】:Insert Data with pymysql using inputs使用输入使用 pymysql 插入数据
【发布时间】:2017-06-11 00:31:51
【问题描述】:

我正在处理数据库,但在使用 pymysql 插入一些值时遇到了问题

cur.execute("""INSERT INTO orders (name, size, type, is_done) VALUES (%s, %s, %s, %s)""" 
% (name, size, type, is_done))

name, sizetype 是字符串,is_done 是布尔值

它给了我典型的错误You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near,所以我想问题是',但我该如何解决呢?

编辑

我还应该补充一点,名称值是从 MySQL 数据库中检索的

【问题讨论】:

  • 检查真正执行了哪个查询。 stackoverflow.com/questions/7071166/…我觉得这个链接可以帮到你。
  • 谢谢,但是我看到命令真的执行了,所以死路一条……
  • 那么,你能显示已执行的查询吗?
  • @huhushow 我已经找到问题了,谢谢大家:)

标签: python mysql python-3.x pymysql


【解决方案1】:

当前公认的解决方案存在SQL injection 漏洞。您不应该使用 % 运算符格式化字符串 - 只需将参数元组作为第二个参数传递,库将处理其余部分。

cur.execute("INSERT INTO orders (name, size, type, is_done) VALUES (%s, %s, %s, %s)",
    (name, size, type, is_done))

另见this answerpymysql documentation

【讨论】:

    【解决方案2】:

    我发现了问题,而不是

      cur.execute("""INSERT INTO orders (name, size, type, is_done) 
      VALUES (%s, %s, %s, %s)""" 
      % (name, size, type, is_done))
    

    我应该做的

    cur.execute("""INSERT INTO orders (name, size, type, is_done) 
     VALUES ("%s", "%s", "%s", "%s")""" 
    % (name, size, type, is_done))
    

    【讨论】:

      【解决方案3】:

      如果您不为 id 输入值。你有一个错误。试试这个查询。

      cur.execute("insert into orders values(%s, %s, %s, %s, %s)", (None, name, size, type, is_done))
      

      id 列的“%s”和“None”。此查询运行我的代码。 注意:不要忘记 commit()

      【讨论】:

        猜你喜欢
        • 2017-03-23
        • 2013-04-25
        • 2019-07-13
        • 2019-01-01
        • 2020-02-02
        • 2021-01-12
        • 2018-10-14
        • 1970-01-01
        • 2019-01-04
        相关资源
        最近更新 更多