2009-08-26 134 views
3

我們,我在python中開發一個實用程序,我有2個對象主要類和一個數據庫幫助器來獲取sqlserver數據。AttributeError:'NoneType'對象沒有屬性'GetDataStore'

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' 

什麼是錯的?

+0

這是什麼? '_ db'? – SilentGhost 2009-08-26 13:19:15

回答

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

看看__new__應該做什麼以及它應該有什麼參數。我想你想用__init__而不是__new__。你特別錯誤的原因是_dbNone

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')")