django 2种方式读取外部的DB

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

上一篇:Java中util.Date通过mybatis向数据库中datetime的操作!


下一篇:mysql登录报错:mysql: error while loading shared libraries: libncurses.so.5: cannot open shared object file: No such file or directory