How to suppress exceptions when execute a SQL query in python - python-3.x

My project is to compare file names located on a folder with names saved in a PostgreSQL database.
I looked into different responses on the SO but nothing worked for me.
Please see below my comments within the source code.
try
cur = db_conn().cursor()
report query = "SELECT ev_report FROM stc_events_master WHERE
si_station_num = %s AND" +
" ev_ins_date BETWEEN to_date(" + "'" + "1/1/2018" + "'" + ",'mm/dd/yyyy')" + "
and TO_DATE('12/31/2018', 'mm/dd/yyyy')"
# files_dict content-> k = '123p34" , value = "DV03S_120124_5-7-2018.pdf"
for k, v in files_dict.items():
cur.execute(report_query, (k,))
# the reports are unique in the database table
query_result = cur.fetchmany(1) #incoming value:DV03S_120124_5-7-2018.pdf
# query returns:
sta = str(query_result[0])
# if a file is not found in the database, the exception happens
# and the code below is not executed. It jumps
# directly to Exception
if len(sta) < 1:
print("no report found in the database")
print("query_results" + sta)
else:
if v.lower() == q_ry.lower():
print("match " + v)
else:
print("no match " + v)
except Exception:
pass
print("In Exception area")
finally:
cur.close()
I want to continue the loop even if nothing is found the database and save a name of the file from the folder which caused the exception. Now, the code stops after the exception.
Thank you for your help.

for k, v in files_dict.items():
cur.execute(report_query, (k,v))
if cur.rowcount == 0:
print("The file is not in the database: " + v)
else:
query_result = cur.fetchmany(3)
sta = str(query_result[0])
file_name_length = len(sta)
q_ry = sta[2: file_name_length-3]
if v.lower() == q_ry.lower():
pass
else:
print("no match after comparing names" + v)
except (Exception, psycopg2.Error) as error:
print("Error fetching data from PG table " + k, error)
finally:
cur.close()

Related

SQL lite search function

So I am new to SQL lite and Python in general...
I'm creating a search function that should return an else statement when the input receives an empty query. Not understanding while I fufill the else statement the whole database is returned instead of the print statement I called.
def search_task():
askjeeves = input("Enter Search Term: ")
cur = con.cursor()
if askjeeves != "" or askjeeves != " ":
cur.execute("SELECT * FROM books WHERE author LIKE'%'||?||'%' ", (askjeeves,))
finalsearch = cur.fetchall()
print(finalsearch)
search_task()
else:
print("No value inputted, program ended. ")
Also tried:
def search_task():
askjeeves = input("Enter Search Term: ")
cur = con.cursor()
if askjeeves != None:
cur.execute("SELECT * FROM books WHERE author LIKE'%'||?||'%' ", (askjeeves,))
finalsearch = cur.fetchall()
print(finalsearch)
search_task()
else:
print("No search input")
input("Do you want to search again? Input 1 for Yes, 0 for No:")
if input == 1:
search_task()
else:
print("Search Ended")
You have a circular dependency here. You are calling the function again in the if.
When it is empty, you have a problem with your checks.
Empty strings in python are False. So
def search_task():
askjeeves = input("Enter Search Term: ")
cur = con.cursor()
if askjeeves and askjeeves != " ":
cur.execute("SELECT * FROM books WHERE author LIKE'%'||?||'%' ", (askjeeves,))
finalsearch = cur.fetchall()
print(finalsearch)
search_task()
else:
print("No search input")
input("Do you want to search again? Input 1 for Yes, 0 for No:")
if input == 1:
search_task()
else:
print("Search Ended")

continue to check all instances version even one raise an error in python?

I have a function in which I am trying to get the version of the db's.i have multiple instances and I am able to connect with all of them.Problem I am facing if any db doesn't connect or command fails for some reason it doesn't continue to next db.All I want it to continue till last instance
def dbversion(user_suffix=None):
try:
db_name_list = abc.getdbstring(env_name=None)
for dbname in db_name_list:
connection = Connection(dbname)
cursor = connection.cursor()
version = connection.version
print(" " + version + " ")
except:
print("Fail")
You can put try block within the loop:
def dbversion(user_suffix=None):
db_name_list = abc.getdbstring(env_name=None)
for dbname in db_name_list:
try:
connection = Connection(dbname)
cursor = connection.cursor()
version = connection.version
print(" " + version + " ")
except:
print("Fail")

How to print the result of JSON to the output file?

The output of the JSON file has multiple responses like the one seen below
"response_code":1
"scan_date":"2011-07-27 03:44:56"
"permalink":"https://www.virustotal.com/gui/file/1caea01fd9a6c6d12e5ca46007e25a4b1eff640060f45de8213e40aa5b47cd57/detection/f-1caea01fd9a6c6d12e5ca46007e25a4b1eff640060f45de8213e40aa5b47cd57-1311738296"
"verbose_msg":"Scan finished, information embedded"
"total":43
"positives":19
The below code will get the value of "positives" in the JSON output and then print it to the file.
# DOES THE HASH EXISTS IN VT DATABASE?
if response == 0:
print(hash + ": UNKNOWN")
file = open(output,"a")
file.write(hash + " 0")
file.write("\n")
file.close()
# DOES THE HASH EXISTS IN VT DATABASE?
elif response == 1:
positives = int(json_response.get("positives"))
if positives >= 3:
print(hash + ": MALICIOUS")
file = open(output,"a")
file.write(hash + " " + str(positives))
file.write("\n")
file.close()
else:
print(hash + ": NOT MALICIOUS")
file = open(output,"a")
file.write(hash + " 0")
file.write("\n")
file.close()
else: print(hash + ": CAN NOT BE SEARCHED")
So the result of the current code will be something like the below
0136b7453cedf600d6f6aab7900901d3 19
I am trying to get the value of "permalink" in the JSON results and print it in the same output file. So the output must look like the below
0136b7453cedf600d6f6aab7900901d3 19 https://www.virustotal.com/gui/file/1caea01fd9a6c6d12e5ca46007e25a4b1eff640060f45de8213e40aa5b47cd57/detection/f-1caea01fd9a6c6d12e5ca46007e25a4b1eff640060f45de8213e40aa5b47cd57-1311738296
How do I achieve this?
Thanks
You can read it the same way you read the positive values.
elif response == 1:
positives = int(json_response.get("positives"))
permalink = json_response.get("permalink")
if positives >= 3:`enter code here`
print(hash + ": MALICIOUS" + " | URL:" + permalink)
file = open(output,"a")`enter code here`
file.write(hash + " " + str(positives))
file.write("\n")
file.close()

Keep getting else/elif invalid syntax error

Currently I'm writing a code where I want to ask motor values from motor controller using raspberry pi. However my code is throwing InvalidSyntax Error in else and elif statements. I've already read about if and elif statements in python, but I can't figure out mistake by myself. The code is below:
def motor_values():
while 1:
command_1 = '?A '+str(1)+' \r' #Asking first motor current
command_2 = '?A '+str(2)+' \r' #Asking second motor current
counter = 0
#First motor current
if counter = 0:
ser.write(command_1.encode()) #string to bytes
data_1 = ser.readline().decode().strip() #bytes to string
#Checking if data is received and extracting current value
if 'A=' in data_1:
value_1 = int(data_1.split('=')[1])
print("Motor Current(Channel 1): " + str((value_1) + " Ampers")
counter += 1
else:
print("Message is not received")
#Second motor current
elif counter == 1:
ser.write(command_2.encode()) #string to bytes
data_2 = ser.readline().decode().strip() #bytes to string
if 'A=' in data_2:
value_2 = int(data_2.split('=')[1])
print("Motor Current(Channel 2): " + str((value_2) + " Ampers")
counter += 1
else:
print("Message is not received")
else:
counter = 0
A few syntax errors here:
use == in the if clause condition
#First motor current
if counter == 0: #
remove one of the two ( in str((value_2)
print("Motor Current(Channel 1): " + str(value_1) + " Ampers")
print("Motor Current(Channel 2): " + str(value_2) + " Ampers")
you missed closing brace in print function
print("Motor Current(Channel 1): " + str(value_1) + " Ampers")

Split text field on json

I want to do some data analysis on a json file generated from twitter.
The field that I need is the text field which contain the tweet itself.
your contribution is highly appreciated
while tweetCount < maxTweets:
try:
if (max_id <= 0):
if (not sinceId):
new_tweets = api.search(q=search_query, count=tw_block_size)
else:
new_tweets = api.search(q=search_query, count=tw_block_size, since_id=sinceId)
else:
if (not sinceId):
new_tweets = api.search(q=search_query, count=tw_block_size, max_id=str(max_id - 1))
else:
new_tweets = api.search(q=search_query, count=tw_block_size, max_id=str(max_id - 1), since_id=sinceId)
if not new_tweets:
print("Collecte terminee.")
break
for tweet in new_tweets:
day = tweet.created_at.strftime('%Y-%m-%d')
with open( "%s/%s_tweets.json" % (output_dir, day), 'a') as f:
f.write(json.dumps(tweet._json))
f.write('\n')
tweetCount += len(new_tweets)
print("{0} tweets téléchargés".format(tweetCount))
max_id = new_tweets[-1].id
except tweepy.TweepError as e:
print("an error was occured to continue , run the following command:")
print("python collect.py -s {0} -o {1} -u {2}".format(search_query, output_dir, max_id))
print("")
print("Error : " + str(e))
break

Resources