从数据库中的表中获取所有记录的正确方法是什么?
我的想法是:
import MySQLdb
Class User:
def __init__(self, id):
self.db = MySQLdb.connect(host="localhost", user="root",passwd="password",db="database")
self.cur = self.db.cursor()
self.id = id
self.cur.execute("SELECT * FROM `user` WHERE `id` = %s;", (id))
res = self.cur.fetchone()
self.firstName = res[1]
self.lastName = res[2]
self.email = res[2]
Class UserManager:
def __init__(self):
self.db = MySQLdb.connect(host="localhost", user="root",passwd="password",db="database")
self.cur = self.db.cursor()
def get_all_users(self):
self.cur.execute("SELECT `id` FROM `user`;")
rows = self.cur.fetchall()
users = []
for row in rows:
users.append(User(row[0]))
return users
我确定有更好的方法吗?如何创建用户?