【问题标题】:python mysql fetch querypython mysql 获取查询
【发布时间】:2009-09-11 20:20:39
【问题描述】:
def dispcar ( self, reg ):
                print ("The car information for '%s' is: "), (reg)
                numrows = int(self.dbc.rowcount) #get the count of total rows
                self.dbc.execute("select * from car where reg='%s'") %(reg)
                for x in range(0, numrows):
                    car_info = self.dbc.fetchone()
                    print row[0], "-->", row[1]

上面的代码给出了这个错误:

self.dbc.execute("select * from car where reg='%s' " %(reg)
TypeError: unsupported operand type(s) for %: 'long' and 'str'

谁能帮我理解为什么会出现这个错误?

仅供参考:reg 是用户在函数 getitem 中输入的 raw_input var i,并将 reg var 作为参数传递给此函数。

【问题讨论】:

    标签: python mysql


    【解决方案1】:

    这让几乎所有使用 MySQLDB 的人感到困惑。您正在将参数传递给执行函数,而不是进行 python 字符串替换。查询字符串中的 %s 更像是一个准备好的语句,而不是 python 字符串替换。这也可以防止 SQL 注入,因为 MySQLDB 会为您进行转义。正如你之前所拥有的(使用 % 和字符串替换),你很容易被注入。

    1. 不要使用引号。 MySQLDB 会将它们放在那里(如果需要)。
    2. 使用 , 而不是 %。同样,您将元组作为参数传递给执行函数。

      self.dbc.execute("select * from car where reg=%s" , (reg,))

    【讨论】:

      【解决方案2】:

      我认为这行只是将括号放在错误的位置:

      self.dbc.execute("select * from car where reg='%s'") %(reg)
      

      您正在对 execute() 的结果使用 % 和 reg。

      改成:

      self.dbc.execute("select * from car where reg='%s'" % reg)
      

      self.dbc.execute("select * from car where reg='%s'", reg)
      

      取决于它是否会为您进行参数替换。

      【讨论】:

      • 这确实有点帮助。但它没有从数据库中获取数据?还有什么问题吗?
      • 可能与在执行查询之前获取行数有关?
      【解决方案3】:

      你把括号弄错了:

      self.dbc.execute("select * from car where reg=%s" , (reg,))
      

      您使用 fetchone 进行循环的任何特定原因(在这个丑陋的循环中,其范围基于行数,当您在执行查询之前得到它时可能为零)?

      做事

      for car_info in self.dbc.fetchall():
          ....
      

      【讨论】:

        猜你喜欢
        • 2021-11-02
        • 1970-01-01
        • 2010-10-28
        • 1970-01-01
        • 2011-05-09
        • 2014-03-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多