报错,MySQLdb库里没有conn?
来源:3-3 python查询mysql数据库
冰红茶煮蛋
2019-03-12
import MySQLdb
class MysqlSearch(object):
def get_conn(self):
# 获取链接
try:
self.conn = MySQLdb.connect(
host = '127.0.0.1',
user = 'root',
password = '',
db = 'news',
port = 3306,
charset = 'utf8'
)
except MySQLdb.Error as e:
print('Error: %s' % e)
def close_conn(self):
try:
if self.conn:
# 关闭连接
self.conn.close()
except MySQLdb.Error as e:
print('Error: %s' % e)
# 获取数据
def get_one(self):
# 准备 SQL
sql = 'SELECT * FROM `news` WHERE `types` = %s ORDER BY `created_at` DESC;'
# 找到cursor
cursor = self.conn.cursor()
# 执行SQL
cursor.execute(sql,('百家', ))
# 拿到结果
print(dir(cursor))
rest = cursor.fetchone()
# 处理数据
print(rest)
# 关闭cursor/连接
cursor.close()
self.close_conn()
def main():
obj = MysqlSearch()
obj.get_one()
if name == ‘main’:
main()
报错信息:
Traceback (most recent call last):
File “test_tranning_1.py”, line 48, in
main()
File “test_tranning_1.py”, line 45, in main
obj.get_one()
File “test_tranning_1.py”, line 31, in get_one
cursor = self.conn.cursor()
AttributeError: ‘MysqlSearch’ object has no attribute ‘conn’
Repl Closed
写回答
1回答
-
冰红茶煮蛋
提问者
2019-03-12
老师,我在以上代码添加 __init__(self):self.get_conn()之后,虽然没有报错但是没有理解是为什么,请指导一下,谢谢
012019-03-13
Python操作三大主流数据库-MySQL+MongoDB+Redis
一次实战同时掌握Python操作MySQL,MongoDB,Redis 三大数据库使用技巧
2024 学习 · 376 问题
相似问题