默认数据库已经安装OK, 并且MySQLdb(Python连接MySQL的模块)已经安装ok

未使用配置文件方式连接mysql:


def accessDb(request):
    import MySQLdb
    db = MySQLdb.connect(db='jetty', user='root', passwd='mysql', host='localhost', charset='utf8')
    cursor = db.cursor();
    cursor.execute('SELECT name FROM book ORDER BY name')
    names = [row[0] for row in cursor.fetchall()]
    for name in names:
        print 'bookName:', name
    return HttpResponse('access DB successful!')

-------------------------------------------------------------------------
使用配置文件方式连接mysql:
修改settings.py

DATABASES = {
    'default': {
        'ENGINE': 'mysql',                    # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'jetty',                      # Or path to database file if using sqlite3.
        'USER': 'root',                      # Not used with sqlite3.
        'PASSWORD': '*****',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '3306',                      # Set to empty string for default. Not used with sqlite3.
    }
}
使用 python manage.py shell以django配置启动python交互解释器:

执行
>>> from django.db import connection
>>> cursor = connection.cursor()
如果没有错误产生,则配置成功!




 
posted on 2016-10-01 16:33  神圣兽国窝窝乡独行侠  阅读(577)  评论(1编辑  收藏  举报