Python和MySQL连接问题(mysqldb-api)

2024-09-30 04:32:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我有配置.ini公司名称:

[mysql]
host=localhost
port=3306
user=root
passwd=abcdefgh
db=testdb
unix_socket=/opt/lampp/var/mysql/mysql.sock

我上这个班:

^{pr2}$

还有这个:

#!/usr/bin/env python  
from mysql import MySQL

class Incident( MySQL ):

    def getIncidents( self ):
        self.cursor.execute("""*VALID QUERY*""")
        return self.cursor.fetchall()

最后是:

import subprocess, os, alarm
from Queue import Queue
from incident_model import Incident

fileQueue = Queue()

def enumerateFilesPath():
  global fileQueue
  incident = Incident()
  incidents = incident.getIncidents()
  for i in incidents:
    fileQueue.put("MD5")

def main():
    global fileQueue
    enumerateFilesPath()

输出:

Traceback (most recent call last):
File "./mwmonitor.py", line 202, in

main() File "./mwmonitor.py", line 184, in main
enumerateFilesPath() File "./mwmonitor.py", line 86, in
enumerateFilesPath
incident = Incident() File "/usr/share/mwanalysis/core/mysql.py",
line 23, in init
self.unix_socket) File "/usr/lib/pymodules/python2.6/MySQLdb/init.py",
line 81, in Connect
return Connection(*args, **kwargs) File
"/usr/lib/pymodules/python2.6/MySQLdb/connections.py",
line 170, in init
super(Connection, self).init(*args, **kwargs2)
TypeError: an integer is required
Exception AttributeError: "'Incident'
object has no attribute 'cursor'" in
0xa03d46c>> ignored

如果有人能帮助检测并纠正错误,将不胜感激。 提前谢谢。在


Tags: infrompyimportselfinitusrdef
3条回答

我怀疑它希望port是一个整数而不是一个字符串。尝试:

self.port   = int(config.get("mysql","port"))

您的__del__方法引起了混乱。具体地说,它指的是self.cursor和{},如果MySQLdb.Connect引发异常(这似乎就是发生的事情),则可能永远不会创建它们。在

我建议你修改你的类如下:

class MySQL( object ):

    def __init__( self ):

        self.conn   = None
        self.cursor = None

        self.host   = config.get("mysql","host")
        self.port   = config.get("mysql","port")
        self.user   = config.get("mysql","user")
        self.passwd = config.get("mysql","passwd")
        self.db     = config.get("mysql","db")
        self.unix_socket = config.get("mysql","unix_socket")

        self.conn   = MySQLdb.Connect(self.host,
                                      self.port,
                                      self.user,
                                      self.passwd,
                                      self.db,
                                      self.unix_socket)

        self.cursor = self.conn.cursor ( MySQLdb.cursors.DictCursor )

    def __del__( self ):
        if self.cursor is not None:
            self.cursor.close()
        if self.conn is not None:
            self.conn.close()

这不能解决问题,但应该能提供更好的诊断。在

现在来看看你遇到的实际问题。我强烈怀疑您以错误的顺序为Connect提供参数,或者类型不太正确,或者是这些行中的某些东西。要引用Connection.__init__的docstring:

^{pr2}$

“强烈建议您只使用关键字参数。”我建议您在调用MySQLdb.Connect时这样做。另外,请确保portint,而不是字符串。在

我不确定这是否是连接错误。你查过事故模式的类型了吗? TypeError: an integer is required Exception AttributeError: "'Incident'object has no attribute 'cursor'" in

相关问题 更多 >

    热门问题