AttributeError: 'NoneType' object has no attribute 'execute' 错误的解决

运行Python连接mysql数据,查询表格中的数据时报了如下错误AttributeError: 'NoneType' object has no attribute 'execute' 的解决方案

python get_uv_pv_compute_results_from_database.py 
Traceback (most recent call last):
  File "get_uv_pv_compute_results_from_database.py", line 116, in
    obi_get_pv_uv_result_from_database.get_day_pv_uv_from_mysql()
  File "get_uv_pv_compute_results_from_database.py", line 73, in get_day_pv_uv_from_mysql
    res_num = self.execute_pv_uv(sql_get_day_pv_uv_results)
  File "get_uv_pv_compute_results_from_database.py", line 40, in execute_pv_uv
    return self.conn_pv_uv.execute(sql)
  File "/home/simth/2222/db.py", line 33, in execute
    return self.cursor.execute(sql)
AttributeError: 'NoneType' object has no attribute 'execute'

解决方案:

1.mysql数据库没有正确连接,你确认所以参数都对吗?没有漏掉哪个?比如端口。

def Connect(self, *args, **kwargs):
        self.conn = MySQLdb.connect(*args, **kwargs)
        self._cursor = self.conn.cursor()

2、在使用mysql的mysql语句进行查询等操作之前,应该先连接mysql数据库,然后进行查询等操作,最后在完成操作之后,一定要关闭连接

def connect(self): 
    self.connection = MySQLdb.connect(host=self.my_host, user=self.my_user, passwd=self.my_passwd,  db=self.my_db, port=int(self.my_port), charset=self.my_charset)         
     self.cursor = self.connection.cursor() 

def close(self): 
    self.cursor.close() 
    self.connection.close() 

def execute(self, sql): 
    return self.cursor.execute(sql) 

def fetchall(self): 
    return self.cursor.fetchall() 

def commit(self): 
    #self.cursor.close()  
    self.connection.commit()

你可能感兴趣的:(mysql,Python,数据库)