how to use try and except in python? - python

I am trying to get the user_id from the sqlite3 database in python and store in in an array. This is what I have tried:
LIST_ARRAY=[]
def start(bot, update):
value = update.message.from_user.id
print("VALUE first: ", value)
try:
for row in connection.execute("SELECT *from userdetails WHERE user_id=?", (value,)):
print(row)
user_id, full_name, address, phone_number, email = row
data = [user_id]
LIST_ARRAY[0] = data[0]
except:
print(LIST_OF_ADMINS)
It doesn't get the value please help me to sort this out.
My data variable doesn't get added in the list array

i cant help you with the database issue but i can answer the question of "How to use try and except in python"
Try and Except are used in python to handle errors when they occur in your code as shown below
x=[0,'It Worked',2]
try:
print(x[4])
except IndexError:
print("Oh No there was an error")
try:
print(x[1])
except IndexError:
print("Oh No there was an error")
so in the example i made above i created an array with 2 ints and a string... I then "TRY" to print the contents in x[4] which do not exist which results in a IndexError... because i told the program to print(x[4]) and the error that i prepared for occurred the "EXCEPT" statement is executed and the code beneath it is also executed
the output of the code is:
'Oh No there was an error'
'It Worked'

Related

why do Syntax error (python) doesn't work?

I want to print a message in case the user made a mistake while writing the code but it doesnt work I also tried to add NameError exception, it only works if I raise an exception.Thank you for helping.
`
def cncours(nvcours,num_cours):
try :
sql="Update cours set nomC=%s where num_cours=%s"
result=cursor.fetchone()
cursor.execute(sql,(nvcours,num_cours))
print("Operation Done.")
except TypeError:
print("Plz put the name between quotes")
`
Each DB implementation (MySQL, sqlite,...) may raise their particular exceptions. So instead of catching a general exceptions, you may catch errors depending on the specific DB, then on the particular type (e.g. SyntaxError). I suggest to provoque a syntax error on your SQL statement then see what type is (e.g. errorcode or exception type) then catch it.
For instance, the MySQL connector raises error numbers:
import mysql.connector as cn
try:
#...
except cn.Error as err:
print("Something went wrong: {}".format(err))
if err.errno == errorcode.ER_BAD_TABLE_ERROR: #
Here are some MySQL Error Code Ranges
If you are using MySQLdb:
import MySQLdb
try:
#...
cursor.execute(sql)
res = cursor.fetchone()
# ...
except MySQLdb.Error, e:
print "MySQLdb.Error: {}".format(e.args)
Depending on your schema (column types) and the type from the input variable, you may use:
sql="Update cours set nomC='%s' where num_cours=%s" # Added quotes on the first replacement
Besides what you are asking, I think that the command order is inverted.
sql="Update cours set nomC=%s where num_cours=%s"
cursor.execute(sql,(nvcours,num_cours)) # First
result=cursor.fetchone() # Second
print("Operation Done.")
https://www.tutorialspoint.com/python/python_database_access.htm
# execute SQL query using execute() method.
cursor.execute("SELECT VERSION()")
# Fetch a single row using fetchone() method.
data = cursor.fetchone()

Python - EOF/BOF exception when using GetRows() function (from MDX query)

I wrote this code to retrieve data from a cube:
rs = win32com.client.Dispatch('ADODB.RecordSet')
rs.__init__
conn = win32com.client.Dispatch('ADODB.Connection')
conn.__init__
conn.CommandTimeout=3000
conn.Open(connString)
#Retrieving data
try:
rs.Open(mdxQuery, conn, 1, 3)
except Exception as e:
print("An error occured while trying to retrieve data:")
print(str(e))
sys.exit(1)
try:
t=rs.GetRows()
except Exception as ex:
print(str(ex))
it seems the mdx query is ok, and retrieve some result (I can see it from debug mode)
but when I try to assign the result of GetRows() function to a variable, it fails, with the following message:
ADODB.Field : Either BOF or EOF is True, or the current record has been deleted. Requested operation requires a current record.
It seems to me GetRows() function is not able to handle NULL values. Is there a way to tell that method to skip NULL values or just fill it with blanks, and avoid this error?
Thanks

determine type of exception by psycopg2

I'm using python with psycopg2. the following snippet produces some sort of error, but i'm not able to get any output, so i can't handle the error
cur = conn.cursor()
try:
cur.execute("INSERT INTO mqtt.records(client, id_type, value) VALUES (%(str)s, %(int)s, %(float)s)", (topic[1], switchCase(topic[-1]), msg.payload)
except psycopg2.Error as e:
print(e)
conn.commit()
cur.close()
i'm pretty sure it's some sort of typecast error, but it's not catched by the except psycopg2.Error as e:. if i'm using a general except: to catch any exceptions, it catches. but then i don't know how to get the error-message
using except Exception as e: i got the message 'arguments can't be mixed' which led me to figure that ... VALUES (%(str)s, %(int)s, %(float)s) isnt working.
instead i had to do typecasting on the (str(topic[1]), int(switchCase(topic[-1])), float(msg.payload)) part.
so i basicly missunderstood the docs. shame on me.

pyodbc UPDATE throws an exception

I'm making a python program that does Elo calculations for an Azure SQL database. The problem is with the last two 'cursor.execute' commands (the UPDATEs).
I took out part of the code before posting here to make it smaller, but all the variables are properly passed from the find_winner and find_loser methods-- the print commands show the right value.
When I run the program as is, it prints the change in ratings and the message from the except block. When I comment out the UPDATE methods, it doesn't print the except message. The only reason I can come up with is that the variables from the tuple from find_winner and find_loser aren't being entered into the SQL statement properly.
I tried running it with ? and '%s' instead of winner_new_rating and winner_id, but none of the 3 versions worked.
Is there something obvious I'm missing? What's the proper way of entering parameters stored in variables?
def rate():
try:
(winner_rating,winner_name,winner_id) = find_winner()
(loser_rating,loser_name,loser_id) = find_loser()
cursor = conn.cursor()
print(winner_name, "wins", winner_rating, "-->", winner_new_rating)
print(loser_name, "loses:", loser_rating, "-->", loser_new_rating)
cursor.execute("UPDATE KIDS SET Rating = winner_new_rating WHERE LocalID = winner_id")
cursor.execute("UPDATE KIDS SET Rating = loser_new_rating WHERE LocalID = loser_id")
conn.commit()
except:
print("Rate method error")
This is the correct syntax:
try:
cursor.execute("UPDATE KIDS SET Rating = ? WHERE LocalID = ?",
str(winner_new_rating), winner_id)
cursor.execute("UPDATE KIDS SET Rating = ? WHERE LocalID = ?",
str(loser_new_rating), loser_id)
except DatabaseError as e:
print(str(e))

How to access content of declared Variable in python in my POSTGRES sql query

I am just getting my hand dirty with python, hence my question might look silly. Yeah, I have the following code as per of a class. The declared variable in python was to accepted input from the user and then cross checked the content of the variable with an POSTGRES SQL statement.
See the code below;
def view_user(self):
self.contact_modify = input('Please enter name to modify : ')
contact_modify = self.contact_modify
try:
con = self.db_conn()
print('We are connected to the db now')
except:
print('I can not find your database connection here')
try:
print(contact_modify) # to check the content of the variable
con.execute("SELECT * FROM phone WHERE address_name = :'contact_modify'")
print(contact_modify) # To check the contents of the variable
while True:
row = con.fetchone()
if row == None:
break
print(row[1],row[2],row[3])
except:
print("Error displaying your data")
I can get the content of the declared variable named 'contact_modify' at all line of code where I print it, but my POSTGRES SQL is not getting the content hence my EXCEPT part of the code is been execute. I am on POSGRES-9.3 and python 3.4 on 64 Windows10 Machine.
Try This:
con.execute("""SELECT * FROM phone WHERE address_name ='%s';"""%(contact_modify))
If not work then do as #Daniel Roseman said. remove try and except and see the actual error.
You should pass your variable manually, like this:
conn.execute("SELECT foo FROM table where bar = '%s'" % var)
Also, you can use .format() method.

Categories

Resources