Python MySQL 获取查询

2 投票
3 回答
2345 浏览
提问于 2025-04-15 14:16
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中从用户输入的一个变量,我把这个reg变量作为参数传递给这个函数。

3 个回答

1

你的括号用错了:

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

你为什么要用这种丑陋的循环来调用fetchone(这个循环的范围是基于行数的,而行数在你执行查询之前就可能是零)?

其实可以直接这样做:

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

这让很多使用MySQLDB的人感到困惑。你在调用execute函数时传递的是参数,而不是在做Python字符串替换。查询字符串中的%s更像是一个预处理语句,而不是Python的字符串替换。这种方式还可以防止SQL注入,因为MySQLDB会为你处理转义字符。如果你之前使用%和字符串替换的方式,就容易受到注入攻击。

  1. 不要使用引号。MySQLDB会自动添加(如果需要的话)。
  2. 用逗号,替代百分号%。再次强调,你是把一个元组作为参数传递给execute函数。

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

3

我觉得这一行的括号放错地方了:

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)

这要看它是否会为你做参数替换。

撰写回答