I've tried the following query with Django,
def search(search_text):
q = Info.objects.filter(title__contains=str(search_text))
print q.query
The query that get printed is
SELECT "d"."id", "d"."foo" FROM "d_info" WHERE "d_info"."title" LIKE %hello% ESCAPE '\'
The query fails because the text after LIKE doesn't have quotes around it. The query succeeds when I run the query on the sql prompt with quotes around the text after LIKE like below
SELECT "d"."id", "d"."foo" FROM "d_info" WHERE "d_info"."title" LIKE '%hello%' ESCAPE '\'
How do I get Django to add the quotes around the search_text so that the query succeeds ?
I'm using Djanog with sqlite3
I tried this out with Postgresql 8.3. The query is generated without quotes. However executing the filter returns a valid queryset with expected instances. Can you try executing
q = Info.objects.filter(title__contains=str(search_text))
print q.count()
and see if it works?
Posting my comment above as the answer
It so turns out the query works within Django, but when asked to print the query and if I copy the query printed and execute it in a mysql shell or sqlite shell, it doesn't work.
Django is probably printing the query wrong
Related
I am currently working with cx_oracle
Here with SELECT statements I am able to use the fetchall() function to get rows.
But how to get the outputs for queries that fall under Data Definition Language (DDL) category.
For example, after executing a GRANT statement with cursor.execute(), the expected output assuming the query is valid would be,
"GRANT executed successfully"
But how do I get this with cx_oracle, Python.
The answer is that you have print it yourself, which is what SQL*Plus does.
DDL statements are statements not queries because they do not return data. They return a success or error condition to the tool that executed them, which can then print any message. In your case the tool is cx_Oracle. There isn't a way to get the type (GRANT, CREATE etc) of the statement automatically in cx_Oracle. Your application can either print a generic message like 'statement executed successfully', or you can extract the first keyword(s) from the SQL statement so you can print a message like SQL*Plus does.
Hi I want to execute query using sqlcmd so I am calling it using subprocess.call() . This process sometimes its working but in loop it does not work. It only the execute the last argument. Please help below is the sample code I am trying-
import subprocess
host = 'hostname'
db = 'SQLTest'
sqlcmd = "C:\Program Files\Microsoft SQL Server\100\Tools\Binn\SQLCMD.EXE"
query = "INSERT INTO [dbo].[Test](type,ident,lat,long,y_proj,x_proj,new_seg,display,color,altitude,depth,temp,time,model,filename,ltime) VALUES ('TRACK','ACTIVE LOG','40.79015493','-77.85914183','4627311.94501541','1779470.5827101','False','False','255','351.979858398438','0','0','2008/06/11-14:33:33','eTrex Venture','','2008/06/11 09:33:33')"
for x in range (0,5):
subprocess.call([sqlcmd,'-S' ,host, '-d', db, '-Q', query])
Or is there any other method. I even tried pymysql module. But it shows authentication error.
I got the error. It was related to the query I was passing. The query was reading from a text file. So it had spaces in them except the last query. and for single testing I was using the last query. After fixing that it worked.
That's a very creative solution!
When you say " in loop it does not work", could you tell us what's happening? Is there an error message? Does it run, but no data is inserted in the table? Can you get this to work properly outside a loop?
The first thing I notice is
sqlcmd = "c:\program files\...."
You might want to make that a raw string, by putting an "r" in front of the quotes, like so:
sqlcmd = r"c:\program files\...."
That will prevent Python from trying to interpret the backslash as a special characters.
It looks like you're trying to talk to a SQL Server, so pymysql is not going to help (that's for talking to a MySQL Server). I would suggest looking into pyodbc or pymssql as an alternative.
I'm trying to execute a raw query that is built dynamically.
To assure that the parameters are inserted in the valid position I'm using named parameters.
This seems to work for Sqlite without any problems. (all my tests succeed)
But when I'm running the same code against MariaDB it fails...
A simple example query:
SELECT u.*
FROM users_gigyauser AS u
WHERE u.email like :u_email
GROUP BY u.id
ORDER BY u.last_login DESC
LIMIT 60 OFFSET 0
Parameters are:
{'u_email': '%test%'}
The error I get is a default syntax error as the parameter is not replaced.
I tried using '%' as an indicator, but this resulted in SQL trying to parse
%u[_email]
and that returned a type error.
I'm executing the query like this:
raw_queryset = GigyaUser.objects.raw(
self.sql_fetch, self._query_object['params']
)
Or when counting:
cursor.execute(self.sql_count, self._query_object['params'])
Both give the same error on MariaDB but work on Sqlite (using the ':' indicator)
Now, what am I missing?
edit:
The format needs to have s suffix as following:
%(u_email)s
If you are using SQLite3, for some reason syntax %(name)s will not work.
You have to use :name syntax instead if you want to pass your params as {"name":"value"} dictionary.
It's contrary to the documentation, that states the first syntax should work with all DB engines.
Heres the source of the issue:
https://code.djangoproject.com/ticket/10070#comment:18
How can I convert a sql where clause string to a sqlalchemy query? I'm assuming I already know the table.
I'm building an Angular webapp which hits a Flask API for data. Flask is using sqlalchemy to query the db. jQuery-QueryBuilder fromSQL (http://querybuilder.js.org/plugins.html#import-export) exports filters as raw SQL which I want to pass back to the api, parse, and query.
For example:
where_str = "name LIKE '%BOB%' AND fruit != 'pineapple'"
would get converted to:
session.query(Table).filter(Table.name.like('%BOB%')).filter(Table.fruit != 'pineapple)
Tagging blaze because odo might be what I need.
You can try to execute session.query(Table).filter(where_str). It worked for me on SQLAlchemy v0.5.8.
You can also build the whole SQL statement string and use the Connection.execute() method to execute it. Either way, passing SQL statements as strings directly from the webpage to the application can be very dangerous.
You don't need to filter twice to add an AND you can do this:
session.query(Table).filter(Table.name.like('%BOB%'), Table.fruit != 'pineapple)
I have a function, where I get a string as parameter. I want to save this string to a database. So I have a command like:
sql_command = """INSERT INTO some_table(some_text_row) VALUE (
'{0}');""".format(some_text)
But the parameter can contain characters like '. So I need to replace this sort of characters. I do this with this function:
some_text = given_parameter.replace("'", r"\'")
But now comes the strange behavior: Sometimes, I get a result of \\' and sometimes I get a result of \'. I want to have the second one.
To give you more information: The given_parameter is the HTML code of a webpage. I get the HTML code from the library called requests
Does anyone have some tipps?
Don't construct the query using string formatting - this is unsafe, you are making it vulnerable to SQL injections.
Instead, parameterize the query and let the mysql driver worry about quotes:
sql_command = """
INSERT INTO
some_table(some_text_row)
VALUES
(%s)"""
cursor.execute(sql_command, (some_text, ))