Python 的数据库操作必须要映射字段么?

最近学习 Python 通过 Flask 接触到 SQLAlchemyMongoDB 的内容,但看下来貌似都要在对象中映射字段才能用?那这样的话假设数据库中有数百张表的话就要创建同样数量的对象文件么?之前用的是 PHPLaravel 框架,是可以直接 DB::table(...).select() 这样获取数据的,所以 Python 能这样操作么?不懂请教

阅读 1.9k
2 个回答
import pymysql

connection = pymysql.connect(host='localhost',
                             user='username',
                             password='password',
                             db='mydb',
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)

try:
    with connection.cursor() as cursor:
        sql = "SELECT * FROM mytable"
        cursor.execute(sql)
        result = cursor.fetchall()
        print(result)
finally:
    connection.close()

你可以用官方的 pymongo 驱动程序直接进行数据库操作,没必要为每个表定义映射类。

import pymongo

client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["mydatabase"]
collection = db["mycollection"]

# 查询数据
results = collection.find({})

for result in results:
    print(result)

可以,你要操作 mysql,就直接用 pymysql,不是一定要 orm

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题