Unable to fetch data using select query - python

I have used GCP cloud SQL with dailogflow CX there is one table QuestionPageMapping_test it stored all padeId and FlowID of questions that asked by bot. It is used for redo activity. If user wants to go back to any question then user can select that question according to that question select query will fetch pageID of that question and user can start their conversation from that question again. But select query does not work properly at some instance.It work for some questions.
option=r=re.sub(r'[^\w\s]', ' ', option)
connection2 = connector.connect(os.environ['DB_Instance_Name'],"pymysql",database='bot_info',user="root",password=os.environ['DB_Password'])
cursor2 = connection2.cursor(pymysql.cursors.DictCursor)
query1= f"select * from QuestionPageMapping_test where questions ='{option}'"
print(query1)
cursor2.execute(query1)
rows = cursor2.fetchall()
print(rows)
for row in rows:
global option2
option2=row["pageId"]
connection2.close()
query="set #row_number=0;"
cursor.execute(query)
query = f"select * FROM (select *,(#row_number:=#row_number + 1) AS R_NUM from {session_id} order by timestamp) as a1 where pageId='{option2}'"
print(query)
I tried this code,in that option variable is used for to store question that is present at dailoflow cx's page. when select query fail then rows is empty that is why it is not entering into for loop and because of that I am getting NameError: name 'option2' is not defined" for next query.
(https://i.stack.imgur.com/559BB.png)

Related

how to run update sql query based on select query results using python

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, )]

Delete values from db2 table if exist in schema in Python

i want to ask for a little help about my problem. I have sql query that get all the tables from some schema and put those tables in a list in Python. For example:
tablesList = ['TABLE1','TABLE2',...]
After i get this list of tables that i want i go one more time through each table in a for loop for example:
for t in range(len(tables)):
table = tables[t]
...
#here i want to check if this table exist in some db2 schema and if exist delete content
#of this table, otherwise go with next table check and don't delete content
Query for checking will be:
sql = """SELECT COUNT(*) FROM SYSIBM.SYSTABLES
WHERE TYPE = 'T'
AND CREATOR = 'MY_SCHEMA'
AND NAME = '{table}';""".format(table = table)
cursor.execute(sql)
rows_count = cursor.fetchone()
if rows_count is None:
pass
else:
delete...

Updating a record with a value from another table - MySQL (Python)

I am trying to update a value in one table (csms) in MySQL from another table (serviceppl). I have attached the query I wrote and both tables, but the query does not work. It does not produce any error, but the record doesn't get updated. Help!
query = "select*from csms where feedback in('null', 'I expect a better one', 'Bad one! Need one again')"
mycursor.execute(query)
p = mycursor.fetchall()
for i in p:
query_upserv = """update csms inner join serviceppl on csms.product = serviceppl.speciality
set serviceppl.name = csms.serviceman where csms.product = '{}'""".format(i[4])
mycursor.execute(query_upserv)
mycon.commit()
If you want to update the column serviceman of the table csms then you must fix your SET clause:
set csms.serviceman = serviceppl.name

Read things out of database WHERE 'id'=

I am trying to build an examine (Dutch = overhoor) program in Python. Here's my code:
cursor = cnx.cursor()
willekeurig = random.randint(0,9)
query = ('SELECT FRwoord, NLwoord FROM unite8app1 WHERE "id"=willekeurig')
cursor.execute(query)
for (NLwoord, FRwoord) in cursor:
print("Wat is de vertaling van: " + FRwoord + "?")
vertaling = input()
if vertaling == NLwoord:
print("Well done")
else:
print("Helaas")
for (FRwoord, NLwoord) in cursor:
print(FRwoord,NLwoord)
print(query)
cnx.close
I am trying to get a random question based upon the id of that question in my database. I tried some alternatives like:
WHERE 'id'=1
WHERE 'ID'=1
etc
But it doesn't want to work if I run my program (after pressing enter) it says that NLwoord and FRwoord aren't defined, but when I remove that bit of code it works just fine. (if I have just 1 item in my database)
My question is how to grab a random id from my database? I have included some pictures of the database.
http://updo.nl/file/37e39c15.JPG
http://updo.nl/file/1de64d64.JPG
Right now you are not passing the value of willekeurig, but the text willekeurig. Try these two lines for your query & execute insted:
query = "SELECT FRwoord, NLwoord FROM unite8app1 WHERE id=%s"
cursor.execute(query, (willekeurig,))
Have you tried this without any quotes around id?
You should also be able to use:
SELECT FRwoord, NLwoord FROM unite8app1 ORDER BY RAND() LIMIT 1

How can one optimize this MySQL count algorithm?

I have 2 tables; one is users and the other records user actions. I want to count the number of actions per user and record this in the users table. There are ~100k user and the following code takes 6 hours! There must be a better way!
def calculate_invites():
sql_db.execute("SELECT id, uid FROM users")
for row in sql_db:
id = row['id']
uid = row['uid']
sql1 = "SELECT COUNT(1) FROM actions WHERE uid = %s"
sql_db.execute(sql1, uid)
count_actions = sql_db.fetchone()["COUNT(1)"]
sql = "UPDATE users SET count_actions=%s WHERE uid=%s"
sql_db.execute(sql, (count_actions, uid))
You can do this all as one statement:
update users
set count_actons = (select count(*) from actions a where a.uid = users.uid)
No for loop. No multiple queries. Do in SQL what you can do in SQL. Generally looping over rows is something you want to do in the database rather than in the application.
Offered only as an alternative since Gordon's answer is probably faster:
update users
from (
select uid, count(*) as num_actions
from actions
group by uid
) x
set count_actions = x.num_actions
where users.uid=x.uid

Categories