Python third-party library series Xi.--django.db's connection library

Source: Internet
Author: User

Usually use Django to read and write data in the database is the model, direct Molel.objects.filter (Q ()) or Model.objects.get (Q ()) and other reading data. However, this q () query SQL statement must conform to the Django ORM specification, which today summarizes the use of connection libraries and native SQL statements to read and write to the database.
From django.db Import connectionsql_str = "SELECT * FROM book" cursor = Connection.cursor () cursor.execute (SQL_STR) domain_ And_record_db_datas = Cursor.fetchall ()
Today, a special wonderful problem, fixed an afternoon to solve, is the SQL statement like method. Take a look at how it evolves:

1. The usual like method is:

SQL_STR = "SELECT * from book where name is like ' xxx '"

This statement is equivalent to:
SQL_STR = "SELECT * from book WHERE name = ' xxx '"
2. In order to blur the query, this should be:
SQL_STR = "SELECT * from book where name is like '%xxx% '"
3. In Python, however, "%" is a special character and requires two "percent" to represent a "%", so it is written like this:

SQL_STR = "SELECT * from book where name like '%%xxx%% '" Print sql_str# select * from book where name like '%xxx% '

If this is the case, the printed SQL statement can be run under the SQL command line, but the following error is reported in my Django:

' Cursor ' object has no attribute ' _last_executed '
I found on the internet for a long time, all said as long as the "percent" on the line, my is an error. So I boldly added "%%%%", tell the compiler I this is a percent semicolon, incredibly ok!
4. Sum up, in Django if Add 2 "%" also reported wrong, add 4 "%", so write this:

From django.db Import connectionsql_str = "SELECT * from book where name like '%%%%xxx%%%% '" cursor = Connection.cursor () cu Rsor.execute (sql_str) Domain_and_record_db_datas = Cursor.fetchall ()
It worked!

Python third-party library series Xi.--django.db's connection library

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.