Devinwon / article

0 stars 0 forks source link

operate mysql in django(not ORM) #8

Open Devinwon opened 6 years ago

Devinwon commented 6 years ago

本例说明如何在django中操作Mysql数据库

  1. 以代码为例说明 在views.py中,示例编码如下

    import MySQLdb
    def index(request):
    conn=MySqldb.connect(
        host='127.0.0.1',
        port=3306,
        user='root',
        passwd='root',
        db='dbname',
        charset='utf8',     #须与建立数据库时编码一致
    
        )
    cursor=conn.cursor()   #定义游标
    cursor.execute("SELECT * FROM firstapp_article")
    results=cursor.fetchmany()
    
    articles=[]
    for result in  results:
        articles.append(
            {
                # 这里与数据库中定义的表相匹配关联
                #result[0]为id
                'title':result[1],
                'content':result[2],
                'views':result[3],
                'likes':result[4],
                'createtime':result[5],
                'editors_choice':result[6],
                'cover':result[7],
                'url_image':result[8],
            }
    
        )
        context={}
        context['articles']=articles
    return render(request,'index.html',context)
  2. 在模板templates当中,这样引用

    {% for v in articles %}
    <--#注意上面articel后面没有.all-->
    {{v.title}}
    {% endfor %}