Hi i have try this query in php which is running fine and i have to do this same in python
$select=mysql_query("SELECT DISTINCT A.entity_id AS entity_id ,A.email AS email,A.catquizid AS style_quiz_score ,A.catquizquesans AS style_quiz_answer,A.created_at AS date_joined,A.is_active AS is_active ,B.attribute_id AS attribute_id,B.value AS info FROM `customer_entity` AS A inner join `customer_entity_varchar` AS B on A.entity_id=B.entity_id WHERE B.`attribute_id` IN (1,2) limit 10",$conn);
$arr=array();
while($result= mysql_fetch_assoc($select))
{
if(!isset($arr[$result['entity_id']]['lastname'])){
$arr[$result['entity_id']]['firstname'] = $result['info'];
}
$arr[$result['entity_id']]['lastname'] = $result['info'];
$arr[$result['entity_id']]["email"]=$result['email'];
$arr[$result['entity_id']]["style_quiz_score"]=$result['style_quiz_score'];
$arr[$result['entity_id']]["style_quiz_answer"]=$result['style_quiz_answer'];
$arr[$result['entity_id']]["date_joined"]=$result['date_joined'];
$arr[$result['entity_id']]["is_active"]=$result['is_active'];
$arr[$result['entity_id']]["username"]=normalize_str($result['email']);
}
and in python i have tried this
def customer_migrate(request):
cursor = connections['migration'].cursor()
cursor.execute("SELECT DISTINCT A.entity_id AS entity_id ,A.email AS email,A.catquizid AS style_quiz_score ,A.catquizquesans AS style_quiz_answer,A.created_at AS date_joined,A.is_active AS is_active ,B.attribute_id AS attribute_id,B.value AS info FROM customer_entity AS A inner join customer_entity_varchar AS B on A.entity_id=B.entity_id WHERE B.attribute_id limit 4 ")
row = cursor.fetchall()
how can i use the while loop in the python query ,
Use fetchone() or just iterate through the cursor:
row = cursor.fetchone()
while row is not None:
print row
row = cursor.fetchone()
or
for row in cursor:
print row
Related
I am trying to update a row in an sql table based on results of a select query using python. How to add same so that if results found in select query we should be able to run update query and print as list updated, if not exit saying no result found to update table
cursor = conn.cursor()
cursor.execute(
"select * from student where email = 'xyz.com'"
)
student = cursor.fetchall()
print(student)
for row in student:
cursor.execute(" Update student set value = 0 where email = 'xyz.com'")
`
You don't need to do a separate SELECT, you can just use an OUTPUT clause to have your UPDATE statement return the value(s) from the row(s) that are updated. For example, with pyodbc:
sql = """\
UPDATE student SET value = 0
OUTPUT INSERTED.student_number
WHERE email = 'xyz.com' AND (value <> 0 OR value IS NULL)
"""
student_numbers = crsr.execute(sql).fetchall()
print(student_numbers) # [(1001, ), (1003, )]
I am trying to capture the only the record from a PostgreSQL statement. The select statements outputs one row with column named as updated_at and the value is a timestamp- '2008-01-01 00:50:01'. I want to just capture/collect that value so when I call that variable, it just outputs '2008-01-01 00:50:01'.
Here is my code:
def get_etl_record():
pg_hook = PostgresHook(postgre_conn_id="post", schema='schema1')
connection = pg_hook.get_conn()
cursor = connection.cursor()
cursor2 = connection.cursor()
latest_update_query = "select max(updated_at) from my_table group by updated_at"
cursor.execute(latest_update_query)
#results= cursor.fetchall()
columns = [col[0] for col in cursor.description]
rows = [dict(zip(columns, row[0])) for row in cursor.fetchall()]
print(rows)
However this code doesnt give me an output.
Any ideas or suggestions?
There is no way to do what you want, but 3 ways to do very similar:
1.
cursor = connection.cursor()
cursor.execute(sql)
result = cursor.fetchone()
max_updated_at = result[0]
2.
dict_cur = connection.cursor(cursor_factory=psycopg2.extras.DictCursor)
dict_cur.execute('select max(updated_at) as max_updated_at ...')
result = dict_cur.fetchone()
max_updated_at = result['max_updated_at']
3.
nt_cur = connection.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor)
nt_cur.execute('select max(updated_at) as max_updated_at ...')
result = nt_cur.fetchone()
max_updated_at = result.max_updated_at
How to fetch just one column as array in python with pymysql;
for example sql:
select name from users
data:
["Tom", "Ben", "Jon"]
cursor = conn.cursor() # where conn is your connection
cursor.execute('select name from users')
rows = cursor.fetchall()
result_list = [row[0] for row in rows]
I have a list of words in an SQLite database and I want to get the most common value and save it in a variable.I am using python3
here is how I got my most common value.
SELECT emotion,
COUNT(emotion) AS value_occurrence
FROM chatlog
GROUP BY emotion
ORDER BY value_occurrence DESC
LIMIT 1;
May be something like this?
#!/usr/bin/python
import sqlite3
conn = sqlite3.connect('yourdb')
cur = conn.cursor()
cur.execute('''SELECT emotion,
COUNT(emotion) AS value_occurrence
FROM chatlog
GROUP BY emotion
ORDER BY value_occurrence DESC
LIMIT 1''')
rows = cur.fetchall()
for row in rows:
x = row[0]
y = row[1]
print(x,y)
Hell guys just jumped in to python and i'm having a hard time figuring this out
I have 2 queries . . query1 and query2 now how can i tell
row = cursor.fetchone() that i am refering to query1 and not query2
cursor = conn.cursor()
query1 = cursor.execute("select * FROM spam")
query2 = cursor.execute("select * FROM eggs")
row = cursor.fetchone ()
thanks guys
Once you perform the second query, the results from the first are gone. (The return value of execute isn't useful.) The correct way to work with two queries simultaneously is to have two cursors:
cursor1 = conn.cursor()
cursor2 = conn.cursor()
cursor1.execute("select * FROM spam")
cursor2.execute("select * FROM eggs")
cursor1.fetchone() #first result from query 1
cursor2.fetchone() #first result from query 2
It doesn't. The return value from cursor.execute is meaningless. Per PEP 249:
.execute(operation[,parameters])
Prepare and execute a database operation (query or
command)...
[...]
Return values are not defined.
You can't do it the way you're trying to. Do something like this instead:
cursor = conn.cursor()
cursor.execute("select * FROM spam")
results1 = cursor.fetchall()
cursor.execute("select * FROM eggs")
if results1 is not None and len(results1) > 0:
print "First row from query1: ", results1[0]
row = cursor.fetchone()
if row is not None:
print "First row from query2: ", row