I need to compare the user input date kakko (yyyy-mm-dd format) with the CreateDate and UpdateDate in table productinfo and return the result.
This does not work.
cur.execute("SELECT * FROM `productinfo` WHERE CreateDate > %s-%s-%s AND CreateDate <= (SELECT MAX( UpdateDate ) FROM productinfo) AND Updatedate = (SELECT MAX( UpdateDate ) FROM productinfo) ",kakko)
db.commit()
Try below code
sql ='SELECT
*
FROM
productinfo
WHERE
CreateDate > ? AND CreateDate <= (SELECT
MAX(UpdateDate)
FROM
productinfo) AND Updatedate = (SELECT
MAX(UpdateDate)
FROM
productinfo)';
cur.execute(sql,kakko)
db.commit
cur.execute("SELECT * FROM `productinfo` WHERE CreateDate > '%s'" %(kakko,))
result = cur.fetchall()
works!
Related
I have a pymysql update query that I want to work. It keeps throwing me an error.
mydb = mysql.connector.connect(
host="*****",
user="****",
password="****",
database="database",
port="****"
)
mycursor = mydb.cursor()
mycursor.execute ("""
UPDATE table1
SET BUGS=%s, CODE_SMELLS=%s, VULNERABILITIES=%s
WHERE username = %s
AND time_created = (SELECT MAX(time_created) FROM table1
)
""", (bugs, code_smells, vulnerabilities, username))
mydb.commit()
mydb.close()
mysql.connector.errors.DatabaseError: 1093 (HY000): You can't specify target table 'table1' for update in FROM clause
Try
UPDATE table1
SET BUGS=%s, CODE_SMELLS=%s, VULNERABILITIES=%s
WHERE username = %s
ORDER BY time_created DESC
LIMIT 1
or use a subquery that creates a temp table. So you will not update directly the table you are selecting from.
UPDATE table1
SET BUGS=%s, CODE_SMELLS=%s, VULNERABILITIES=%s
WHERE username = %s
AND time_created =
(
SELECT * FROM
(
SELECT MAX(time_created) FROM table1
) tmp
)
SQL query:
Select *
from table_name
where ID in (123)
and date in (Select max(date)
from table_name
where ID in (123))
I want to pass below mentioned list values one at time in above SQL query and collect results for each ID in list
Package: cx_Oracle
My try:
import cx_oracle
List= {123, 234,345,....}
List1 = []
query = " Select * from table_name where ID in (%s)
and date in (Select max(date) from table_name where ID in (%s))"
for j in List:
cursor1 = db_ora.cursor()
tb = cursor1.execute(query, params= List )
for i in tb:
List1.append(i)
Thank you in advance, let me know if you need more details from my side
If you want to keep it similar to your original code, you can use string formatting
Python 2
import cx_oracle
List= [123, 234,345,....]
List1 = []
masterQuery = " Select * from table_name where ID in (%s)
and date in (Select max(date) from table_name where ID in (%s))"
for j in List:
cursor1 = db_ora.cursor()
newQuery = masterQuery % (j, j)
tb = cursor1.execute(newQuery)
for i in tb:
List1.append(i)
Python 3
import cx_oracle
List= [123, 234,345,....]
List1 = []
masterQuery = " Select * from table_name where ID in {}
and date in (Select max(date) from table_name where ID in {})"
for j in List:
cursor1 = db_ora.cursor()
newQuery = masterQuery.format(j, j)
tb = cursor1.execute(newQuery)
for i in tb:
List1.append(i)
As far as I can tell, Oracle won't accept such a list as a valid parameter. Either store that list of values into a separate table and use it as a source for your query, such as
and t.date in (select max(t1.date) from table_name t1
where t1.id in (select st.id from some_table st)
)
or, if possible, split that comma-separated-values string into rows, e.g.
and t.date in (select max(t1.date) from table_name t1
where t1.id in (select regexp_substr(%s, '[^,]+', 1, level)
from dual
connect by level <= regexp_count(%s, ',') + 1
)
)
Also, I'd suggest you to precede column names with table aliases to avoid possible confusion.
I am trying to write a SELECT query with a WHERE condition and ORDER BY.
I have the query in MySQL and would like to convert it to Python.
This is my Mysql-Query:
SELECT StoreId
, ProductCode
, TotalQuantity
FROM storeinvoicedetails
WHERE StoreId=1
ORDER BY ProductCode
This is what I tried in Python:
sql = "SELECT StoreId,ProductCode,TotalQuantity FROM storeinvoicedetails \
WHERE StoreId = '%d'" % (1) \
"ORDER BY '%s' '%s'" % ('ProductCode','ASC')
query = """SELECT StoreId,ProductCode,TotalQuantity FROM storeinvoicedetails WHERE StoreId={0} ORDER BY ProductCode ASC""".format(store_id)
> sql = "SELECT StoreId,ProductCode,TotalQuantity FROM storeinvoicedetails \
WHERE StoreId = '%d' \
ORDER BY ProductCode ASC" % id
This should work.
STOREID = 1
# make sure you add the last space for every line, otherwise it will look like 'TotalQuantityFROM' causing an error
myQuery = "SELECT StoreId,ProductCode,TotalQuantity " +
"FROM storeinvoicedetails " +
"WHERE StoreId=" + str(STOREID) + " "
"ORDER BY ProductCode"
I wrote the following SQL query. How can I do the same thing in SQLAlchemy?
SELECT
T.campaign_id,
T.spend,
T.id
FROM activity_log T
WHERE T.end_time = (
SELECT MAX( T1.end_time ) FROM activity_log T1
WHERE T1.campaign_id = T.campaign_id and cast(T1.end_time as DATE) = cast(T.end_time as DATE)
);
Below should get you started:
T = aliased(ActivityLog, name="T")
T1 = aliased(ActivityLog, name="T1")
subquery = (
session.query(func.max(T1.end_time).label("end_time"))
.filter(T1.campaign_id == T.campaign_id)
.filter(cast(T1.end_time, Date) == cast(T.end_time, Date))
.correlate(T)
.as_scalar()
)
qry = (
session.query(T.campaign_id, T.spend, T.id)
.filter(T.end_time == subquery)
)
Can someone please explain how I can get the tables in the current database?
I am using postgresql-8.4 psycopg2.
This did the trick for me:
cursor.execute("""SELECT table_name FROM information_schema.tables
WHERE table_schema = 'public'""")
for table in cursor.fetchall():
print(table)
pg_class stores all the required information.
executing the below query will return user defined tables as a tuple in a list
conn = psycopg2.connect(conn_string)
cursor = conn.cursor()
cursor.execute("select relname from pg_class where relkind='r' and relname !~ '^(pg_|sql_)';")
print cursor.fetchall()
output:
[('table1',), ('table2',), ('table3',)]
The question is about using python's psycopg2 to do things with postgres. Here are two handy functions:
def table_exists(con, table_str):
exists = False
try:
cur = con.cursor()
cur.execute("select exists(select relname from pg_class where relname='" + table_str + "')")
exists = cur.fetchone()[0]
print exists
cur.close()
except psycopg2.Error as e:
print e
return exists
def get_table_col_names(con, table_str):
col_names = []
try:
cur = con.cursor()
cur.execute("select * from " + table_str + " LIMIT 0")
for desc in cur.description:
col_names.append(desc[0])
cur.close()
except psycopg2.Error as e:
print e
return col_names
Here's a Python3 snippet that includes connect() parameters as well as generate a Python list() for output:
conn = psycopg2.connect(host='localhost', dbname='mySchema',
user='myUserName', password='myPassword')
cursor = conn.cursor()
cursor.execute("""SELECT relname FROM pg_class WHERE relkind='r'
AND relname !~ '^(pg_|sql_)';""") # "rel" is short for relation.
tables = [i[0] for i in cursor.fetchall()] # A list() of tables.
Although it has been answered by Kalu, but the query mentioned returns tables + views from postgres database. If you need only tables and not views then you can include table_type in your query like-
s = "SELECT"
s += " table_schema"
s += ", table_name"
s += " FROM information_schema.tables"
s += " WHERE"
s += " ("
s += " table_schema = '"+SCHEMA+"'"
s += " AND table_type = 'BASE TABLE'"
s += " )"
s += " ORDER BY table_schema, table_name;"
db_cursor.execute(s)
list_tables = db_cursor.fetchall()
you can use this code for python 3
import psycopg2
conn=psycopg2.connect(database="your_database",user="postgres", password="",
host="127.0.0.1", port="5432")
cur = conn.cursor()
cur.execute("select * from your_table")
rows = cur.fetchall()
conn.close()