
python 数据操作是否需要映射字段?
在 python 中使用 sqlalchemy 或 mongodb 时,你可能遇到需要映射字段的问题。那么,这种映射对于数据库操作是否必需的呢?
答案:不必需
python 中可以使用原生数据库操作库进行直接的数据查询,如:
立即学习“Python免费学习笔记(深入)”;
sqlalchemy 直接查询
使用 pymysql 库:
import pymysql
connection = pymysql.connect(...)
with connection.cursor() as cursor:
sql = "select * from mytable"
cursor.execute(sql)
result = cursor.fetchall()
print(result)mongodb 直接查询
使用 pymongo 库:
import pymongo
client = pymongo.MongoClient(...)
collection = client["mydatabase"]["mycollection"]
results = collection.find({})
for result in results:
print(result)上述代码演示了如何直接执行 sql 查询或 mongodb 查找,而无需映射对象到数据库表。这对于操作多个表或避免创建大量对象文件非常有用。










