文章内容
2019/3/4 16:54:32,作 者: 黄兵
AttributeError: 'Connection' object has no attribute 'execute'
在使用MySQLdb的时候,查询数据,出现了如下错误:
AttributeError: 'Connection' object has no attribute 'execute'
具体代码如下:
# 数据库保存原始数据 mysql_conn = Conn_Config().Conn_MySQL() with closing(Conn_Config().Conn_MySQL()) as cur: # SQL 插入语句 sql = "INSERT INTO visit_time_line_original(time, ip, url,user_agent) \ VALUES (%s, \'%s\', '\%s\', '\%s\')" % \ (item, get_ip, get_url, get_user_agent) try: # 执行sql语句 cur.execute(sql) # cursor.close()
Conn_Config().Conn_MySQL()
具体的实现方式,可以参考这篇文章代码:MySQLdb连接数据库封装
可以对比一下这篇文章:Python 操作 MySQL 数据库
主要是缺少对游标的操作。
出现问题的原因:
没有设置Connection to Cursor方法。
解决方案:
设置Connection to Cursor方法:
cur = connection.cursor()
修改后的代码如下:
with closing(Conn_Config().Conn_MySQL()) as conn_mysql: with closing(conn_mysql.cursor()) as cur: # SQL 插入语句 sql = "INSERT INTO visit_time_line_original(time, ip, url,user_agent) \ VALUES (%s, \'%s\', '\%s\', '\%s\')" % \ (item, get_ip, get_url, get_user_agent) try: # 执行sql语句 cur.execute(sql) # 避免这个错误: Commands out of sync; you can't run this command now cur.close() # 提交到数据库执行 conn_mysql.commit()
之后问题解决。
参考资料:
1、Error : function' object has no attribute 'execute' [closed]
黄兵个人博客原创。
转载请注明出处:黄兵个人博客 - AttributeError: 'Connection' object has no attribute 'execute'
评论列表