zoukankan      html  css  js  c++  java
  • python中使用原生态sql语句

    Django中执行sql语句有两种方式:

    1.object_list=Object.raw('select top 10 from Table where a=1')

    如果你使用的是mysql数据库,这里就会出错,因为MySQL不支持top写法,可以换成:select * from table where a=1 limit 10

    Paginator(list(object_list),8)#这里需要使用list(),主要是将object_list转换为list类型。不然你会在len(object_list)的时候出错,因为object_list没有这个方法

    2.

    from django.db import connection
    cursor = connection.cursor()
    cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])
    row = cursor.fetchone()

    如果你的SQL语句改变了数据库中的数据 -- 比如你使用了 DELETE 或 UPDATE 语句. 你需要调用 connection.commit() 来使你的修改生效. 例子:

    from django.db import connection
    cursor = connection.cursor()
    cursor.execute("DELETE FROM bar WHERE baz = %s", [self.baz])
    connection.commit()

    打印Django里面的sql语句

    from django.db import connection
    test.objects.filter(******)
    print connection.queries

    参考:https://docs.djangoproject.com/en/1.5/topics/db/sql/

    Python中使用mysql

    import MySQLdb 
    db = MySQLdb.connect(host = 'localhost', user = 'root', passwd = '123456', db = 'test',port=3306,charset='utf8') 
    cursor = db.cursor() 
    cursor.execute(´select * from table´) 
    rs = cursor.fetchall() 
    print rs

    返回字典类型

    import MySQLdb 

    import MySQLdb.cursors
    db = MySQLdb.connect(host = 'localhost', user = 'root', passwd = '123456', db = 'test',port=3306,charset='utf8',cursorclass = MySQLdb.cursors.DictCursor) 
    cursor = db.cursor() 
    cursor.execute(´select * from table´) 
    rs = cursor.fetchall() 
    print rs

  • 相关阅读:
    2019.8.15刷题统计
    2019.8.12刷题统计
    2019.8.11刷题统计
    2019.8.10刷题统计
    2019.8.9刷题统计
    2019.8.8刷题统计
    2019.8.7刷题统计
    2019.8.6刷题统计
    xuezhan.org 6.28
    xuezhan.org 6.27
  • 原文地址:https://www.cnblogs.com/smallcoderhujin/p/3059676.html
Copyright © 2011-2022 走看看