Python和MySQL连接问题(mysqldb api)

发布于 2024-11-09 18:24:22 字数 2488 浏览 4 评论 0原文

我有 config.ini:

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

我有这个类:

#!/usr/bin/python
import MySQLdb,ConfigParser
config = ConfigParser.ConfigParser()
config.read("config.ini")

class MySQL( object ):

    def __init__( self ):
        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 ):
        self.cursor.close()
        self.conn.close()

和这个:

#!/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()

输出:

回溯(最近一次调用最后一次):
文件“./mwmonitor.py”,第 202 行,位于

main() 文件“./mwmonitor.py”,第 184 行,在 main
enumerateFilesPath() 文件“./mwmonitor.py”,第 86 行,位于
枚举文件路径
事件=事件()文件“/usr/share/mwanalysis/core/mysql.py”,
第 23 行,在 init
中 self.unix_socket) 文件“/usr/lib/pymodules/python2.6/MySQLdb/init.py”,
第 81 行,在 Connect
返回连接(*args,**kwargs)文件
“/usr/lib/pymodules/python2.6/MySQLdb/connections.py”,
第 170 行,在 init
super(连接, self).init(*args, **kwargs2)
类型错误:需要一个整数
异常属性错误:“'事件'
对象在
中没有属性“光标” 0xa03d46c>>被忽略

如果有人可以帮助检测并纠正错误,我们将不胜感激 提前致谢。

I have config.ini:

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

I have this class:

#!/usr/bin/python
import MySQLdb,ConfigParser
config = ConfigParser.ConfigParser()
config.read("config.ini")

class MySQL( object ):

    def __init__( self ):
        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 ):
        self.cursor.close()
        self.conn.close()

and this:

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

class Incident( MySQL ):

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

and finally this:

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()

Output:

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

If someone can help detect and correct the error would greatly appreciate.
Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

浮云落日 2024-11-16 18:24:22

您的 __del__ 方法引起了混乱。具体来说,它指的是 self.cursorself.conn,如果 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__ 的文档字符串:

    Create a connection to the database. It is strongly recommended
    that you only use keyword parameters. Consult the MySQL C API
    documentation for more information.

    host
      string, host to connect

    user
      string, user to connect as

    passwd
      string, password to use

    db
      string, database to use

    port
      integer, TCP/IP port to connect to

    unix_socket
      string, location of unix_socket to use

    ...

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

Your __del__ method is causing confusion. Specifically, it refers to self.cursor and self.conn which may never get created if, for example, MySQLdb.Connect raises an exception (which is what seems to happen).

I suggest you modify your class as follows:

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()

This won't solve the problem, but should give better diagnostic.

Now to the actual problem that you're experiencing. I strongly suspect that you're supplying the arguments to Connect in the wrong order, or the types aren't quite right, or something along those lines. To quote the docstring for Connection.__init__:

    Create a connection to the database. It is strongly recommended
    that you only use keyword parameters. Consult the MySQL C API
    documentation for more information.

    host
      string, host to connect

    user
      string, user to connect as

    passwd
      string, password to use

    db
      string, database to use

    port
      integer, TCP/IP port to connect to

    unix_socket
      string, location of unix_socket to use

    ...

"It is strongly that you only use keyword parameters." I recommend that you do just that when you call MySQLdb.Connect. Also, make sure that port is an int and not a string.

情徒 2024-11-16 18:24:22

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

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

I suspect it's expecting port to be an integer rather than a string. Try:

self.port   = int(config.get("mysql","port"))
櫻之舞 2024-11-16 18:24:22

我不确定这是否是连接错误。您检查过 event_model 的类型吗?
类型错误:需要一个整数
异常 AttributeError:“'事件'对象没有属性'光标'”

I am not sure if this is a connectivity error. Have you checked the type of the incident_model ?
TypeError: an integer is required
Exception AttributeError: "'Incident'object has no attribute 'cursor'" in

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文