TypeError:'连接'在使用mysqldb的python脚本中,对象不可调用

时间:2017-01-16 06:31:50

标签: python mysql database

import MySQLdb

class database():

 def __init__(self, host, user, pwd, db):

  self.db = MySQLdb.connect(host, user, pwd, db)

  self.cursor = self.db.cursor()

# FUNCTION FOR DATABASE VIEW #
 def db(self):

#SQL command
  sql = "select * from details"
  try:
  self.cursor.execute(sql)

  results = self.cursor.fetchall()

  for row in results:
   print row[0], row [1], row[2]

  except:
   print "error"

#Closing database
 self.db.close()

db = database('localhost', 'root', 'password', 'test')

db.db()

使用此代码,我得到错误,因为连接对象不可调用。 我的目标是创建单个连接对象并将其用于各种SQL查询。我是python脚本的新手。因此,如果有人帮助克服这个错误,那么在我的编码中进一步发展将会非常有用。提前谢谢。

1 个答案:

答案 0 :(得分:0)

确实在数据库类中定义了一个名为def的函数。但是在同一个类的__init__方法中你可以这样做。

self.db = MySQLdb.connect(host, user, pwd, db)

它取代了你刚用MySQLdb连接对象所做的功能。因此错误。

当人们开始使用数据库时,很多人都会为该API创建一个包装器,但这只会增加代码的复杂性。通常数据库API设计得很好。请考虑在没有包装的情况下直接使用它。