代码之家  ›  专栏  ›  技术社区  ›  Shounak Das

如何使用Python连接器使用参数将整数值获取到MySQL数据库中

  •  0
  • Shounak Das  · 技术社区  · 5 年前

    ID . ID的数据类型为整数。代码如下:

    custID = int(input("Customer ID: "))
    executeStr = "SELECT * FROM testrec WHERE ID=%d"
    
    cursor.execute(executeStr, custID)
    custData = cursor.fetchall()
    
    if bool(custData):
        pass
    else:
        print("Wrong Id")
    

    但是代码产生了一个错误,它说:

    mysql.connector.errors.ProgrammingError: 1064 (42000): 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 '%d' at line 1
    

    知道为什么要用整数占位符吗 %d 是在生产这个?

    2 回复  |  直到 5 年前
        1
  •  2
  •   JeffUK    5 年前

    字符串只接受%s或%(name)s,而不接受%d。

    executeStr = "SELECT * FROM testrec WHERE ID=%s"
    

    变量应该在一个元组中,尽管这取决于您使用的版本的实现,但您可能需要使用:

    cursor.execute(executeStr, (custID,))
    

    更多信息请点击此处 https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html

        2
  •  0
  •   Satyajit Satapatathy    5 年前

    您应该尝试%s而不是%d。这是因为MYSQL的数据类型可能是int,但传递给cursor的参数必须是string。

    试试这个:

    custID = int(input("Customer ID: "))
    executeStr  = 'SELECT * FROM testrec WHERE ID=%s'%(custID,)
    
    cursor.execute(executeStr, custID)
    custData = cursor.fetchall()
    
    if bool(custData):
        pass
    else:
        print("Wrong Id")