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