I want to use an SQL output string to query some data in PostgreSQL using Python. I'm using Python 2.7.
For example:
The output string is mike
I want to have mike as 'mike' to be valid as an input.
This is my code:
formated_fix_names = ''.join(author_name_fix_list)).replace(' ', '\'')
The problem is I need to pass this string to an SQL code as name = 'mike':
cursor.execute("select author_name from commits where commit_hash in ("+formated_fix_names+")")
The problem must be at this part I think .replace(' ', '\'').
Do not mess with string manipulation. Psycopg does the right thing by adapting a Python list to a Postgresql array:
author_list = ['John','Mary']
query = """
select author_name
from commits
where commit_hash = any (%s)
"""
print cursor.mogrify(query, (author_list,))
#cursor.execute(query, (author_list,))
Output:
select author_name
from commits
where commit_hash = any (ARRAY['John', 'Mary'])
Notice that the list must be passed to the cursor.execute method wrapped in an iterable.
The in syntax can be used if the list is cast to a tuple:
author_list = ['John','Mary']
query = """
select author_name
from commits
where commit_hash in %s
"""
print cursor.mogrify(query, (tuple(author_list),))
#cursor.execute(query, (tuple(author_list),))
Output:
select author_name
from commits
where commit_hash in ('John', 'Mary')
If you want to turn the string mike into the string 'mike' you can use this expression:
name = "mike"
newName = "'%s'" % name
This turns name, which contains the string mike, into newName, which contains the string mike with single quotes around it, which you should now be able to use. I hope this helps!
You can use double quotes(""), for example:
name = "mike"
result = "'" + name + "'"
Related
I am trying to query salesforce object from python .
the query string contains 'single quote so escape characters added automatically
and it failed because \backslash escape character added in the query
name=David's
sql_query = (
f"SELECT Id FROM contact WHERE Name = '{name}'"
)
Expected string output:
sql_query = SELECT Id FROM contact WHERE Name = 'David's'
Actual string formed by script
sql_query = SELECT Id FROM contact WHERE Name = 'David\'s'
Any help pls
You need to put your name string variable in double quotes. Additionally, the way you are inserting name into the sql_query string is not correct.
Try this:
name = "David's"
sql_query = "SELECT Id FROM contact WHERE Name = " + name
I'm trying to select from a table so that the parameter I input can be nothing but it still will select everything
name = ""
mycursor.execute('SELECT * FROM table WHERE name LIKE "%%%s%%"' (name, ))
I was hoping to have if name is something like "", then everything in the table will be fetched.
With LIKE it will not be possible , however you can achieve it using REGEXP
name = "John Doe"
regexp='^.*$'
value = (regexp if name=="" else name)
query = "SELECT * FROM mysql.user WHERE name REGEXP '{}' ;".format(value)
print(query)
Note: However be wary that if you are looking for a single user, and if there are other user names that matches the string Like "John Doe1" it will return both the entries
I am trying to update the value of a table using Python MySql DB but getting this error.
TypeError: query() argument 1 must be a string or read-only buffer, not tuple.
And I am clueless what is wrong with my answer.
def id_of_unverifedUniversity():
cur3.execute('select id from universities where verified=0 and deleted=0;')
print "===================Unverififed University================"
for row in cur3.fetchall():
#cur3.execute('SELECT id FROM Users where universityId='+str(row['id']))
print row['id']
query = ('SELECT id FROM users where universityId = %s order by id asc limit 1' %(str(row['id'])))
cur3.execute(query)
result = cur3.fetchall()
for y in result:
if y['id']:
print str(y['id'])
print 'update query statred'
query1 = ("""update universities set updatedBy = %s where id=%s""", (str(y['id']),str(row['id'])))
cur3.execute(query1)
i am getting this error in query1
In query1 the operator % seems missed. Which is binding the variables into str
query1 = '''update `universities` set `updatedBy` = %s where `id`=%s''' % (str(y['id']),str(row['id']))
I think you have the wrong formatting for the string replacement in query1, although I'm more familiar with .format().
Try:
query1 = ("""update universities set updatedBy = {} where id={}""".format(str(y['id']),str(row['id'])))
The problem is that your query1 is a tuple.
query1 = ("""update universities set updatedBy = %s where id=%s""", (str(y['id']),str(row['id'])))
I have some comments for you here:
Don't use triple quotes for one-line string.
Use format function
You don't need to cal str to call str method of your object. format or %s will do it for you - will not be superfluous method call.
So your code could be like this one:
query1 = "update universities set updatedBy = {} where id={}".format(y['id'], row['id'])
Today i am using the sql_debug(True) that helps me to see the queries but without the values.
How could i see how ponyorm translate the query with values ?
Thank you very much.
This is an example of query i'm using.
with db_session:
access = select(p for p in Access if raw_sql('( lower(first_name) = lower($first_name) and lower(last_name) = lower($last_name) ) '
'or ( lower(first_name) = lower($last_name) and lower(last_name) = lower($first_name) ) '
'or (lower(facebook_url) = lower($facebook_url)) '
'or (lower(twitter_url) = lower($twitter_url)) '
'or (lower(linkedin_url) = lower($linkedin_url)) '))
.order_by(desc(Access.twitter_url),desc(Access.facebook_url),desc(Access.linkedin_url),
desc(Access.facebook_url))
print(access.get_sql())
I use
logging.getLogger(__name__).debug('SQL:\n\n\t\t\t%s\n', '\n'.join(unicode(x) for x in request._construct_sql_and_arguments()[:2]).replace('\n', '\n\t\t\t'))
for that.
For example,
19:30:01.902 data.py:231 [DEBUG] SQL:
SELECT "x"."_id", "x"."filename", "x"."_created", "x"."_updated"
FROM "reports" "x"
WHERE "x"."_id" <= ?
AND "x"."_created" >= ?
(50, '2019-04-17 19:30:01.900028')
will be printed out.
You can use set_sql_debug(debug=True, show_values=True).
Reference here.
There is a method called get_sql()
query_obj = select(c for c in Category if c.name.startswith('v'))
sql = query_obj.get_sql()
print(sql)
output:
SELECT "c"."id", "c"."name"
FROM "category" "c"
WHERE "c"."name" LIKE 'v%%'
code continue:
for obj in query_obj:
print('id:', obj.id, 'name:', obj.name)
output:
id: 1 name: viki
here is a link to the docs https://docs.ponyorm.com/api_reference.html#Query.get_sql
You can log the sql or simply print it.
Update:
OP updated the question:
If the sql query has a variable like $name it is passed as a sql parameter.
first_name = 'viki'
query = select(c for c in Category if raw_sql('( lower(name) = lower($first_name))'))
query.get_sql()
so get_sql() will return the value with a placeholder, and the output will look like this:
'SELECT "c"."id", "c"."name", "c"."age"\nFROM "Category" "c"\nWHERE ( lower(name) = lower(?))'
If we want no placeholders should be there in the query then we can avoid passing direct sql to query and instead build it separately in python.
Like this:
query = select(c for C in Category if c.name == 'viki')
query.get_sql()
output:
'SELECT "c"."id", "c"."name", "c"."age"\nFROM "Category" "c"\nWHERE "c"."name" = \'viki\''
Let's say i have a python list of customer id like this:
id = ('12','14','15','11',.......)
the array has 1000 values in it, and i need to insert the customer name to a table based on the ids from the list above.
my code is like:
ids = ",".join(id)
sql = "insert into cust_table(name)values(names)where cust_id IN('ids')"
cursor.execute(sql)
after running the code, i get nothing inserted to the table. What mistake do i have?
Please help :(
You need to format the string.
ids = ",".join(id)
sql = "insert into cust_table(name)values(names)where cust_id IN('{ids}')"
cursor.execute(sql.format(ids= ids))
Simply writing the name of a variable into a string doesn't magically make its contents appear in the string.
>>> p = 'some part'
>>> s = 'replace p of a string'
>>> s
'replace p of a string'
>>> s = 'replace %s of a string' % p
>>> s
'replace some part of a string'
>>> s = 'replace {} of a string'.format(p)
>>> s
'replace some part of a string'
In your case this would mean:
>>> sql = "insert into cust_table (name) values (names) where cust_id IN ('%s')"
>>> ids = ", ".join(id)
>>> cursor.execute(sql % ids)
although I strongly suspect that you have a similar problem with names.
In order to avoid possible sql injection problems, it would be preferable to use a "parameterized statement". This would look something like:
>>> sql = 'insert into ... where cust_id IN %s'
>>> cursor.execute(sql, (id,))
Some database connectors for python are capable of this, but yours probably isn't.
A workaround might be something like
>>> params = ', '.join(['%s']*len(id))
>>> sql = 'insert into ... where cust_id IN (%s)' % params
>>> cursor.execute(sql, id)