[英]python class definition problrm
this my first python code i am trying to connect to a database , i defined a class called Database in a python file called mysqlConnection.py这是我尝试连接到数据库的第一个 python 代码,我在名为 mysqlConnection.py 的 python 文件中定义了一个名为 Database 的类
but when i run the code i get this error :但是当我运行代码时,我收到此错误:
Traceback (most recent call last):
File "mysqlConnection.py", line 3, in <module>
class Database:
File "mysqlConnection.py", line 27, in Database
db = Database()
my code is :我的代码是:
import MySQLdb
class Database:
host = "localhost"
user = "root"
passwd = "root"
db = "pitest"
def __init__(self):
self.connection = MySQLdb.connect( host = self.host,
user = self.user,
passwd = self.passwd,
db = self.db)
def query(self, q):
cursor = self.connection.cursor( MySQLdb.cursors.DictCursor )
cursor.execute(q)
return cursor.fetchall()
def __del__(self):
self.connection.close()
if __name__ == '__main__':
db = Database()
q = "DELETE FROM users"
db.query(q)
q = """
INSERT INTO users (title, fname, sname, age, email)
VALUES ('A', 'Z', 'BIG Z', '20', 'raspberrypi@example.com'),
('B', 'X', 'BIG X', '30', 'raspberrypi@example.com'),
('C', 'Y', 'BIG Y', '24', 'raspberrypi@example.com'),
('A', 'W', 'BIG W', '29', 'raspberrypi@example.com')
"""
db.query(q)
q = """
SELECT * FROM users WHERE title = 'A'
"""
allreturnedusers = db.query(q)
for user in allreturnedusers:
print "Found: %s " % user['fname']
can any one help me please ?有人可以帮我吗?
您的代码从该行开始缩进不正确
if __name__ == '__main__':
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.