I have this query in python:
ssim_group = [S1200,S1300]
query = '''select WIPMessageCnt from waferdata where recipename in (%s) and equipment = ?
and runtype = ? order by stopts desc limit 1''' % (','.join(ssim_grp))
print query
Current result
select WIPMessageCnt from waferdata where recipename in (S1200,S1460) and equipment = ?
and runtype = ? order by stopts desc limit 1
Expected result should be like this
select WIPMessageCnt from waferdata where recipename in ('S1200','S1460') and equipment = ?
and runtype = ? order by stopts desc limit 1
The list should have single qoutation on each element when I try to put them inside the IN parameter on SQL. How can I achieve this?
ssim_group = ['S1200', 'S1300']
query = '''select WIPMessageCnt from waferdata where recipename in ('%s') and equipment = ? and runtype = ? order by stopts desc limit 1''' % ("','".join(ssim_group))
Related
I'm trying to format a PostgreSQL query in python and that query has to have '%' between the name of a survey so I can filter surveys by name.
Here is the code:
sql = """select survey_data
from survey_data.survey_data
where codigo_do_projeto like '%s%'
ORDER BY data_de_inicio_da_coleta desc
limit %s
offset %s"""
However it throws this error:
"unsupported format character 'P' (0x50) at index 79"
I don't know how to make python ignore the "%" character.
You have to escape the %.
sql = """select survey_data
from survey_data.survey_data
where codigo_do_projeto like '%%'||%s||'%%'
ORDER BY data_de_inicio_da_coleta desc
limit %s
offset %s"""
Or you can do:
search_val = '%search_term%'
sql = """select survey_data
from survey_data.survey_data
where codigo_do_projeto like %s
ORDER BY data_de_inicio_da_coleta desc
limit %s
offset %s"""
cur.execute(sql, [search_val, val2, val3])
You need to put the survey_name part inside single quotes:
sql = """SELECT survey_data
FROM survey_data.survey_data
WHERE project_code like '%{0}%'
ORDER BY starting_date desc
LIMIT {1}
OFFSET {2}*{1}""".format(survey_name,items_per_page,page_number)
I am trying to pass data into a nested sqlite3 query in python and I get the following error
Incorrect number of bindings supplied. The current statement uses 2, and there are 1 supplied.
x = uid
sql_query1 = """SELECT title FROM movies WHERE addedBy != ? AND mid NOT IN (SELECT mid FROM ratings WHERE uid = ?);"""
data = (uid, x)
cursor.execute(sql_query1, [data])
movies = cursor.fetchall()
I'm guessing the problem might be that x = uid, I have also tried data = (uid, uid) and cursor.execute(sql_query1, [uid]).
Parameters can be explicitly numbered, and the same value used for all instances of a given number:
sql_query1 = """
SELECT title
FROM movies
WHERE addedBy != ?1 AND mid NOT IN (SELECT mid FROM ratings WHERE uid = ?1);"""
cursor.execute(sql_query1, (uid,))
You need to supply as many parameters as you have question marks.
cursor.execute("""
SELECT title
FROM movies
WHERE addedBy != ?
AND mid NOT IN (SELECT mid FROM ratings WHERE uid = ?);
""", [uid, uid])
movies = cursor.fetchall()
Suppose I have this multiple-process Python-MySql query:
self.calculateLeadTime = ("""SET #lastDate = (SELECT sessionDate FROM stock
WHERE product = (%s)
ORDER BY stocksessionID DESC LIMIT 1);
SET #secondLastDate = (SELECT sessionDate FROM stock WHERE product = (%s)
ORDER BY stocksessionID DESC LIMIT 1, 1);
SET #leadTime = (SELECT DATEDIFF(#lastDate, #secondLastDate));
SET #lastStockSessionID = (SELECT stocksessionID
FROM stock WHERE product = (%s) ORDER BY stocksessionID DESC LIMIT 1);
UPDATE stock SET leadTime = (#leadTime)
WHERE stocksessionID = #lastStockSessionID;""", (self.productID.get(), self.productID.get(), self.productID.get()))
self.query = self.cur.execute(self.calculateLeadTime, multi=True)
for self.cur in self.results:
print('cursor:', self.cur)
if self.cur.with_rows:
print('result:', self.cur.fetchall())
self.cn.commit()
I am subject to the error:
stmt = operation.encode(self._connection.python_charset)
AttributeError: 'tuple' object has no attribute 'encode'
I have read the MySql Python documentation regarding multi=True when executing multiple SQL statements via Python. However, my implementation does not work. Any ideas?
Currently, you are passing a tuple as first argument in the cursor.execute call when it expects a single scalar query string in first argument and tuple/list of parameters in second argument:
self.calculateLeadTime = """SET #lastDate = (SELECT sessionDate
FROM stock
WHERE product = (%s)
ORDER BY stocksessionID DESC LIMIT 1);
SET #secondLastDate = (SELECT sessionDate
FROM stock WHERE product = (%s)
ORDER BY stocksessionID DESC LIMIT 1, 1);
SET #leadTime = (SELECT DATEDIFF(#lastDate, #secondLastDate));
SET #lastStockSessionID = (SELECT stocksessionID
FROM stock WHERE product = (%s)
ORDER BY stocksessionID DESC LIMIT 1);
UPDATE stock
SET leadTime = (#leadTime)
WHERE stocksessionID = #lastStockSessionID;
"""
self.query = self.cur.execute(self.calculateLeadTime,
params=(self.productID.get(), self.productID.get(), self.productID.get()),
multi=True)
By the way, MySQL supports JOIN in UPDATE statements for a single statement. Run below with two parameters:
UPDATE stock s
INNER JOIN
(SELECT product, MAX(stocksessionID) AS MaxID
FROM stock
WHERE product = %s
GROUP BY product
) agg_id
ON s.stocksessionID = agg_id.MaxID
INNER JOIN
(SELECT product, MAX(sessionDate) As MaxDate
FROM stock
GROUP BY product) max_dt
ON max_dt.product = s.product
INNER JOIN
(SELECT product, MAX(sessionDate) As SecMaxDate
FROM stock
WHERE sessionDate < ( SELECT MAX(sessionDate)
FROM stock
WHERE product = %s )
GROUP BY product
) sec_max_dt
ON max_dt.product = max_dt.product
SET leadTime = DATEDIFF(MaxDate, SecMaxDate);
I am unsure, if this will work or counts even as multiple queries, because Multi = true is for multiple Resultsets from SELECTS.
You must add teh data for the %s
self.query = self.cur.execute(self.calculateLeadTime,('product','product','product') , multi=True)
I have been trying to execute the following query, but it doesn't give me any output.
self.db.execute("SELECT * FROM patients WHERE patients.doctorid = (SELECT id FROM doctors WHERE username = '%s' % (usr)), callback=self.add_response)
I tried to execute the same query by hardcoding the values and it gives me the correct output.
select * from patients where patients.doctorid = (select id from doctors where username = 'admin');
Can someone tell whats the error?
Try to execute it like this:
self.db.execute("SELECT * FROM patients WHERE patients.doctorid = (SELECT id FROM doctors WHERE username = '%s')" % (usr), callback=self.add_response)
I closed the SQL query with " and fixed the parentheses.
You can also try as shown here:
self.db.execute("SELECT * FROM patients WHERE patients.doctorid = (SELECT id FROM doctors WHERE username = '%s';", (usr), callback=self.add_response)
i have the following sql script.
SELECT *
FROM movies
LEFT JOIN possession
ON movies.id = possession.movie_id
AND possession.master_id = ?
WHERE possession.id is NULL
ORDER BY movies.id DESC
and need help to illustrate in sqlalchemy.
Please can someone help me?
The following doesn't work:
movies = movie.Movie.query.join(possession.Possession, movie.Movie.id == possession.Possession.movie_id)\
.filter(possession.Possession.master_id == session.get('userId'))\
.filter(not_(possession.Possession.id)).order_by(movie.Movie.id.desc()).all()
Thank you very much!
Cheers
The most direct way to translate your SQL query is the ORM query below:
qry = (session.query(Movie)
.outerjoin(Possession, and_(Movie.id == Possession.movie_id, Possession.master_id == master_id))
.filter(Possession.id == None)
.order_by(desc(Movie.id))
)
movies = qry.all()
produces:
SELECT movies.id AS movies_id, movies.name AS movies_name
FROM movies LEFT OUTER JOIN possessions ON movies.id = possessions.movie_id AND possessions.master_id = :master_id_1
WHERE possessions.id IS NULL ORDER BY movies.id DESC
I also think this would be the faster implementation compared to an alternative of using any (see below), which is more concise, but the SQL it produces is not. This also assumes there is a relationship Movie.possessions = relationship(Possession):
qry = (session.query(Movie)
.filter(~Movie.possessions.any(Possession.master_id == master_id))
.order_by(desc(Movie.id))
)
movies = qry.all()
produces:
SELECT movies.id AS movies_id, movies.name AS movies_name
FROM movies
WHERE NOT (EXISTS (SELECT 1
FROM possessions
WHERE movies.id = possessions.movie_id AND possessions.master_id = :master_id_1)) ORDER BY movies.id DESC