首页 > 数据库技术 > 详细

django 2种方式读取外部的DB

时间:2020-09-03 14:06:42      阅读:59      评论:0      收藏:0      [点我收藏+]

For retrieving the data, you have two options:

1) You can create Django models that correspond to your tables in the MySQL database.

You can do this manually, or you can use the "inspectdb" command with manage.py to give yourself a good starting point. Then do something like this:

def myview(request):
  rows = MyModel.objects.using(‘mysql‘).all()
  return render_to_response("mytemplate.html", {"rows" : rows })

参考:https://docs.djangoproject.com/en/dev/topics/db/multi-db/

2) You can manage the connections and queries manually within your app. This is perfectly valid within a view:

def myview(request):
  conn = MySQLdb.connect("connection info here")
  try:
    cursor = conn.cursor()
    cursor.execute("select * from mytable")
    rows = cursor.fetchall()
  finally:
    conn.close()

  return render_to_response("mytemplate.html", {"rows" : rows})

django 2种方式读取外部的DB

原文:https://www.cnblogs.com/lxgbky/p/13606922.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!