AttributeError:'NoneType'对象没有属性'GetDataStore'

时间:2009-08-26 13:16:02

标签: python

我们,我在python中开发一个实用程序,我有2个对象主类和一个数据库帮助器来获取sqlserver数据。

database.py

import _mssql

class sqlserver(object):

    global _host, _userid, _pwd, _db

    def __new__ (self, host, userid, pwd, database):
        _host = host
        _userid = userid
        _pwd = pwd
        _db = database

    def GetDataStore(self, sql):
        conn = _mssql.connect(server='(local)\\sqlexpress', user='sa', password='xxx', database='Framework.Data2')
        conn.execute_non_query('CREATE TABLE persons(id INT, name VARCHAR(100))')
        conn.execute_non_query("INSERT INTO persons VALUES(1, 'John Doe')")
        conn.execute_non_query("INSERT INTO persons VALUES(2, 'Jane Doe')") 

gaemodel.py

import os
import sys
from fwk import system, types, databases

class helper(object):
    pass

def usage(app_name):
    return "Usage: %s <project name>" % (app_name)

def main(argv):
    _io = system.io()

    project_name = argv[1]
    project_home = os.path.join(_io.CurrentDir(), project_name)

    _db = databases.sqlserver('(local)\sqlexpress', 'sa', 'P1lim07181702', 'Framework.Data2')    
    _db.GetDataStore("select name from sysobjects where xtype = 'U' and name not like 'Meta%'")

    str = "from google.appengine.ext import db"
    #for row in cur:
    #    str += "class %s" % row["name"]

    print cur

if __name__ == "__main__":
    if len(sys.argv) > 1:
        main(sys.argv[1:])
    else:
        print usage(sys.argv[0]);

我的问题是当我尝试运行代码时返回此错误

Traceback (most recent call last):
  File "C:\Projectos\FrameworkGAE\src\gaemodel.py", line 28, in <module>
    main(sys.argv[1:])
  File "C:\Projectos\FrameworkGAE\src\gaemodel.py", line 18, in main
_    db. GetDataStore("select name from sysobjects where xtype = 'U' and name not like 'Meta%'")
AttributeError: 'NoneType' object has no attribute 'GetDataStore'

有什么问题?

3 个答案:

答案 0 :(得分:3)

首先:

  • __new__方法应命名为__init__
  • 删除全局_host等行

然后更改__init__方法:

self.host = host
self.userid = userid
etc.

并更改GetDataStore

conn = _mssql.connect(server=self.host, user=self.userid, etc.)

这应该可以解决问题。

我建议你阅读一些关于面向对象的Python。

答案 1 :(得分:1)

看看__new__应该做什么以及应该有什么参数。我想您想使用__init__而不是__new__。您遇到特定错误的原因是_dbNone

答案 2 :(得分:0)

我认为您想要像这样更改databases.py:

import _mssql

class sqlserver(object):

    def __init__ (self, host, userid, pwd, database):
        self.host = host
        self.userid = userid
        self.pwd = pwd
        self.db = database

    def GetDataStore(self, sql):
        conn = _mssql.connect(server=self.host, user=self.userid, password=self.pwd, database=self.db)
        conn.execute_non_query('CREATE TABLE persons(id INT, name VARCHAR(100))')
        conn.execute_non_query("INSERT INTO persons VALUES(1, 'John Doe')")
        conn.execute_non_query("INSERT INTO persons VALUES(2, 'Jane Doe')")