I get an error when I'm trying to convert a field from a mysql query into a variable, my code it's like:
def GetCompanyswithNoResult():
global tabla_db
connection = mysql.connector.connect
mycursor = connection.cursor()
sql = "SELECT * FROM "+ tabla_db +" WHERE RESULT = 0"
mycursor.execute(sql)
myresult = mycursor.fetchone()
ID = myresult[0]
Location = myresult[2]
Market = myresult[3] + " into " + myresult[4]
return [ID, Location, Market]
ID, League, Match = GetMatcheswithNoResult()
the error message that return it's:
Traceback (most recent call last):
File, line 248, in
ID, League, Match = GetCompanywithNoResult()
File , line 123, in GetCompanywithNoResult
ID = myresult[0]
TypeError: 'NoneType' object is not subscriptable
I need some help...
How can I export these values without error?
Related
I am trying to write a python function that updates a postgres database. The table to be updated is given (department)
Below is the function I wrote:
def modify_dept_budget(deptName, newBudget):
connection = None
try:
connection = connector() # This is a function I wrote to connect so I can hide my credentials.
cursor1 = connection.cursor()
query1 = f"select dept_name from department"
cursor1.execute(query1)
results1 = cursor1.fetchall()
results1 = [result[0] for result in results1]
if deptName in results1:
idx = results1.index(deptName)
print(results1[idx])
cursor2 = connection.cursor()
query = f"UPDATE department SET budget = %s WHERE dept_name == {deptName}"
cursor2.execute(query, [newBudget])
cursor3 = connection.cursor()
cursor3.execute(f'SELECT * FROM department')
results2 = cursor3.fetchall()
headers = [item[0] for item in cursor3.description]
df = pd.DataFrame(data = results2, columns = headers)
print(df)
except(Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if connection:
cursor1.close()
cursor2.close()
cursor3.close()
connection.close()
When I run modify_dept_budget('Music', 85000), I get the following error:
Music
column "music" does not exist
LINE 1: ...PDATE department SET budget = 85000 WHERE dept_name == Music
^
---------------------------------------------------------------------------
UnboundLocalError Traceback (most recent call last)
<ipython-input-77-16e7278e3358> in <module>
----> 1 modify_dept_budget('Music', 85000)
<ipython-input-76-80361b6ddf35> in modify_dept_budget(deptName, newBudget)
26 cursor1.close()
27 cursor2.close()
---> 28 cursor3.close()
29 connection.close()
UnboundLocalError: local variable 'cursor3' referenced before assignment
Can anyone help me figure out what is going on?
You have two problems. First, SQL does not use the double == for the equality test. Just plain =. Second, that string literal needs to be quoted. Unless you need a table name or a field name, you won't be using f-strings with SQL. So, do:
query = "UPDATE department SET budget = %s WHERE dept_name = %s"
cursor2.execute(query, [newBudget, deptName])
i am working with ros about 3 month! I work on a robot controller.
i got error in ui about this client:
import sys
import rospy
from database_helper.srv import get_moves, get_movesRequest, get_movesResponse, get_move
def get_data(name: str):
"""This function can extract model names from DB"""
try:
rospy.init_node("get_moves_client")
except:
pass
rospy.wait_for_service('get_moves')
try:
moves = rospy.ServiceProxy('get_moves', get_moves)
except rospy.ServiceException as e:
print(31)
print(e)
return
id = 0
try:
for i in (moves(True).moves):
if i.name == name:
id = i.id
#print(id)
break
except:
print(43)
return
rospy.wait_for_service('get_move')
move = rospy.ServiceProxy('get_move', get_move)
wps = move(id).waypoints
list_of_data = []
try:
for i in range(len(wps)):
print(i)
data = {}
data['x_traj'] = wps[i].x
data['y_traj'] = wps[i].y
data['z_traj'] = wps[i].z
data['time_tarj'] = wps[i].displacement_time_to_next_waypoint
data['order_traj'] = wps[i].order
data['pitch_traj'] = wps[i].pitch
data['roll_traj'] = wps[i].roll
data['yaw_traj'] = wps[i].yaw
data['focus_camer'] = wps[i].camera_focus
data['iris_camera'] = wps[i].camera_iris
data['rail_direction'] = wps[i].rail_direction
data['rail_speed'] = wps[i].rail_speed
data['zoom_camera'] = wps[i].camera_zoom
data['rail_time'] = wps[i].rail_time
data['rail_displacement'] = wps[i].rail_displacement
list_of_data.append(data)
except rospy.ServiceException:
pass
print(list_of_data)
return list_of_data
this client can get data from DB and save with dict and save all dict in a list.
i most write "try/except" and i see 43 number! so i know my except is in for i in range(len(wps)):
the amazing point is, i can run this script and i get answer, but if call this script in my ui, after i using save waypoint and i try to load waypoint, i get ServiceException!
my "add_move.py" code:
from typing import List, Dict
import rospy
from database_helper.srv import add_move
from database_helper.msg import move, waypoint
def _add_move(name: str, wp: List[Dict]):
"""This Function can for send insert query for DB"""
rospy.init_node('add_move_client', anonymous=True)
rospy.wait_for_service('add_move')
_move = move()
_move.name = name
for i in range(len(wp)):
_waypoint = waypoint()
_waypoint.x = wp[i]['x_traj']
_waypoint.y = wp[i]['y_traj']
_waypoint.z = wp[i]['z_traj']
_waypoint.displacement_time_to_next_waypoint = wp[i]['time_tarj']
_waypoint.pitch = wp[i]['pich_traj']
_waypoint.roll = wp[i]['roul_traj']
_waypoint.yaw = wp[i]['ya_traj']
_waypoint.camera_focus = wp[i]['focus_camer']
_waypoint.camera_iris = wp[i]['iris_camera']
_waypoint.camera_zoom = wp[i]['zoom_camera']
_waypoint.rail_speed = wp[i]['speed_rail']
_waypoint.rail_displacement = wp[i]['disp_or_time_rail']
_waypoint.rail_direction = wp[i]['direction_rail']
_move.waypoints.append(_waypoint)
add = rospy.ServiceProxy('add_move', add_move)
return add(_move).id
if __name__ == "__main__":
from random import randint
data = {'x_traj': 12, 'y_traj': 12, 'z_traj': 33, 'time_tarj': 11,
'pich_traj': 13, 'roul_traj': 43, 'ya_traj': 21,
'focus_camer': 11, 'iris_camera': 55, 'zoom_camera': 32,
'disp_or_time_rail': 21, 'speed_rail': 109, 'direction_rail':44,
'joint1_slider': 12, 'joint2_slider': 666, 'joint3_slider': 567,
'joint4_slider': 32, 'joint5_slider': 79, 'joint6_spin': 100
}
wp = []
wp.append(data)
print(_add_move("t1", wp))
my error in terminal without "try/except" is:
Traceback (most recent call last):
File "/opt/ros/noetic/lib/python3/dist-packages/rospy/msg.py", line 223, in deserialize_messages
msg_queue.append(data.deserialize(q))
File "/home/ajax/Documents/iotive/devel/lib/python3/dist-packages/database_helper/srv/_get_moves.py", line 247, in deserialize
val2 = database_helper.msg.waypoint()
File "/home/ajax/Documents/iotive/devel/lib/python3/dist-packages/database_helper/msg/_waypoint.py", line 95, in __init__
self.rail_displacement = 0
AttributeError: 'waypoint' object attribute 'rail_displacement' is read-only
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/opt/ros/noetic/lib/python3/dist-packages/rospy/impl/tcpros_base.py", line 735, in receive_once
p.read_messages(b, msg_queue, sock)
File "/opt/ros/noetic/lib/python3/dist-packages/rospy/impl/tcpros_service.py", line 361, in read_messages
rospy.msg.deserialize_messages(b, msg_queue, self.recv_data_class, queue_size=self.queue_size, max_msgs=1, start=1) #rospy.msg
File "/opt/ros/noetic/lib/python3/dist-packages/rospy/msg.py", line 245, in deserialize_messages
raise genpy.DeserializationError("cannot deserialize: %s"%str(e))
genpy.message.DeserializationError: cannot deserialize: 'waypoint' object attribute 'rail_displacement' is read-only
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/opt/ros/noetic/lib/python3/dist-packages/rospy/impl/tcpros_service.py", line 522, in call
responses = transport.receive_once()
File "/opt/ros/noetic/lib/python3/dist-packages/rospy/impl/tcpros_base.py", line 751, in receive_once
raise TransportException("receive_once[%s]: DeserializationError %s"%(self.name, str(e)))
rospy.exceptions.TransportException: receive_once[/get_moves]: DeserializationError cannot deserialize: 'waypoint' object attribute 'rail_displacement' is read-only
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "./benchmark_new_version_4_1.py", line 730, in get_data_query
self.wp_saver = get_data(response)
File "/home/ajax/Documents/iotive/src/gui/ui/scripts/get_moves_clinet.py", line 36, in get_data
for i in (moves(True).moves):
File "/opt/ros/noetic/lib/python3/dist-packages/rospy/impl/tcpros_service.py", line 442, in __call__
return self.call(*args, **kwds)
File "/opt/ros/noetic/lib/python3/dist-packages/rospy/impl/tcpros_service.py", line 532, in call
raise ServiceException("transport error completing service call: %s"%(str(e)))
rospy.service.ServiceException: transport error completing service call: receive_once[/get_moves]: DeserializationError cannot deserialize: 'waypoint' object attribute 'rail_displacement' is read-only
what is my wrong?
srv/get_move:
int32 id
---
waypoint[] waypoints
srv/get_moves:
bool add_waypoints
---
move[] moves
msg/move:
int32 id
string name
waypoint[] waypoints
msg/waypoint:
int32 id
int32 order
float64 x
float64 y
float64 z
float64 roll
float64 pitch
float64 yaw
int32 camera_focus
int32 camera_iris
int32 camera_zoom
int32 rail_displacement
int32 rail_time
int32 rail_speed
bool rail_direction
int32 displacement_time_to_next_waypoint
So we need to remove service variables when we do not have anything else.
like this:
rospy.wait_for_service('get_moves')
moves = rospy.ServiceProxy('get_moves', get_moves)
id = 0
for i in (moves(True).moves):
if i.name == name:
id = i.id
#print(id)
break
rospy.wait_for_service('get_move')
move = rospy.ServiceProxy('get_move', get_move)
wps = move(id).waypoints
list_of_data = []
for i in range(len(wps)):
print(i)
data = {}
data['order_traj'] = wps[i].order
data['x_traj'] = wps[i].x
data['y_traj'] = wps[i].y
data['z_traj'] = wps[i].z
data['time_tarj'] = wps[i].displacement_time_to_next_waypoint
data['order_traj'] = wps[i].order
data['pitch_traj'] = wps[i].pitch
data['roll_traj'] = wps[i].roll
data['yaw_traj'] = wps[i].yaw
data['focus_camer'] = wps[i].camera_focus
data['iris_camera'] = wps[i].camera_iris
data['rail_direction'] = wps[i].rail_direction
data['rail_speed'] = wps[i].rail_speed
data['zoom_camera'] = wps[i].camera_zoom
data['rail_time'] = wps[i].rail_time
data['rail_displacement'] = wps[i].rail_displacement
list_of_data.append(data)
del move
del moves
print(list_of_data)
return list_of_data
I discovered this last night!
Python 3.6.3 /
Oracle 19c
The following script runs fine till it hits upc_id, = cur.fetchone(). Could someone explain, please what may cause it? If I run the query in database, I get the result back (see below). Is there a way to see exactly what Oracle runs, after variable substitution? I suspect single quotes are not in place for bind variables, but how can I confirm?
import datetime
import cx_Oracle
import db
line_item_sku = 'Y35FLPQ_034Y_M'
x = line_item_sku.split("_")
print (x)
print ("Split-list len: "+ str(len(x)))
if len(x) == 3:
sku_with_dimension = False
elif len(x) == 4:
sku_with_dimension = True
print ("SKU with dimension: " + str(sku_with_dimension))
style_id = x[0]
color_id = x[1]
size_id = x[2]
if sku_with_dimension:
dimension_id = x[3]
print ("Style: "+style_id)
print ("Color: "+color_id)
print ("Size: "+size_id)
conn = db.connect('Galo')
print ("Connected to: " + conn.version)
cur = conn.cursor()
upc_id = cur.var(str)
print ("Assigned return value")
if sku_with_dimension:
sql = ("""
select upc_id
from sku
where business_unit_id = '81'
and style_id = :1
and color_id = :2
and identifier_id = 'EA'
and size_id = :3
and dimension_id = :4
""")
cur.execute(sql,(style_id, color_id, size_id, dimension_id))
else:
sql = ("""
select upc_id
from sku
where business_unit_id = '81'
and style_id = :1
and color_id = :2
and identifier_id = 'EA'
and size_id = :3
""")
cur.execute(sql,(style_id, color_id, size_id))
print ("Determined which query to run")
upc_id, = cur.fetchone()
print (upc_id)
db.disconnect(conn, cur)
Here is the output
'Y35FLPQ', '034Y', 'M']
Split-list len: 3
SKU with dimension: False
Style: Y35FLPQ
Color: 034Y
Size: M
Connected to: 19.0.0.0.0
Assigned return value
Determined which query to run
Traceback (most recent call last):
File "c:/Python/code/test.py", line 66, in <module>
upc_id, = cur.fetchone()
TypeError: 'NoneType' object is not iterable
If I run the query in database, I receive a result back:
I am new to all of this so I'm sorry if I mess this up or have already made a mess. I have two classes a GUI and my MailSorter class in the GUI class I have method which logins, then one that fetches all the EmailIds then finally fetches all the From emails and stores it in a dict. which stores the From email and amount of times it appears and an array with the From email and the ID.
def fetchFrom(self,emailIDs):
EmailAmount = dict()
Email = []
count = 0
for emailId in emailIDs:
#Converts email into string
result2,email_data = self.mail.fetch(emailId,'(RFC822)')
try:
raw_email = email_data[0][1].decode("utf-8")
email_message = email.message_from_string(raw_email)
#Fetches email address sent from
From = email_message["From"]
Email.append((From,emailId))
#print(From)
if From in EmailAmount:
EmailAmount[From] = EmailAmount[From] + 1
else:
EmailAmount[From] = 1
count += 1
if count > 10:
break
except Exception as e:
self.log.append((emailId,e))
def mainScreenInterface(self):
#Process
print("Loading program")
EmailIds = self.Mail.fetchEmailId()
EmailDict, self.EmailArray = self.Mail.fetchFrom(EmailIds)
self.master.geometry("750x600")
self.master.title("Main Screen")
self.destoryWidget()
#New Frame
self.mainScreen = tk.Frame(self.master)
self.mainScreen.pack()
#Labels
mainText = tk.Label(self.mainScreen,text = "All Emails")
mainText.config(font=("Courier","25"))
#Buttons
delete = tk.Button(self.mainScreen,text="Delete", command = self.Delete)
deleteAll = tk.Button(self.mainScreen,text="Delete All", command = self.DeleteAll)
Help = tk.Button(self.mainScreen,text="Help", command = self.Help_)
#Scrollbar
scrollbar = tk.Scrollbar(root)
scrollbar.pack(side="right",fill="y")
#Listbox
self.listbox = tk.Listbox(root,width = root.winfo_screenwidth(), height = 25)
#Attach a scrool wheel to the listbox
self.listbox.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=self.listbox.yview)
#Add items to the list box
count = 1
for x,y in EmailDict.items():
self.listbox.insert(count,(x,y))
count += 1
#Placement
paddingValue = 40
mainText.pack(side="top")
self.listbox.pack(side="top")
delete.pack(side="left",padx=paddingValue)
deleteAll.pack(side="left",padx=paddingValue)
Help.pack(side="left",padx=paddingValue)
def Delete(self):
emailName = self.listbox.get(tk.ANCHOR)[0]
self.Mail.deleteEmail(emailName,self.EmailArray)
So the fetchFrom is from the mailSorter class and the other two are the GUI class, when I call the deleteEmail I get the error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "C:\Users\******\Desktop\Email Sorter v3.py", line 197, in Delete
self.Mail.deleteEmail(emailName,self.EmailArray)
File "C:\Users\******\Desktop\Email Sorter v3.py", line 66, in deleteEmail
self.mail.store(Id[1].strip(), '+X-GM-tk.LabelS', '\\Trash')
File "C:\Python\lib\imaplib.py", line 840, in store
typ, dat = self._simple_command('STORE', message_set, command, flags)
File "C:\Python\lib\imaplib.py", line 1196, in _simple_command
return self._command_complete(name, self._command(name, *args))
File "C:\Python\lib\imaplib.py", line 1027, in _command_complete
raise self.error('%s command error: %s %s' % (name, typ, data))
imaplib.IMAP4.error: STORE command error: BAD [b'Could not parse command']
but when I run it as a text base with no GUI and use an example email it all works fine:
test = MailSorter("hamadnassor5#gmail.com","snerfulbubble1.")
test.login()
EmailIds = test.fetchEmailId()
EmailDict, EmailArray = test.fetchFrom(EmailIds)
test.displayEmails(EmailDict)
test.deleteEmail("Xbox <Xbox#outlook.com>",EmailArray)
test.closeCon()
DeleteMail code
def deleteEmail(self, emailName, EmailArray):
for Id in EmailArray:
if Id[0] == emailName:
print(Id[0])
print(emailName)
print(Id[1])
self.mail.store(Id[1].strip(), '+X-GM-tk.LabelS', '\\Trash')
I am trying to update my treeview by using a delete function but I cannot get the information to transfer over. I have old name and old phone number, and I want to update them with new name and new phone number. I keep encountering the same issue. Here is my code below:
def update():
update_opt = Toplevel()
update_opt.title("Updating")
# grabbing old values from table
old_name = StringVar(update_opt, tree1.item(tree1.focus())['values'][0])
old_phone = StringVar(update_opt, tree1.item(tree1.focus())['values'][1])
Phone = StringVar(update_opt)
Name = StringVar(update_opt)
# creating labels for new/old values
lbl1 = Label(update_opt, text="Old Name: ").grid(row=0,column=1)
pre_name = Entry(update_opt, textvariable=old_name,state='readonly')
pre_name.grid(row=0,column=2)
lbl2 = Label(update_opt, text="New name: ").grid(row=1,column=1)
new_name = Entry(update_opt, textvariable=Name).grid(row=1,column=2)
#New_Name = new_name.get()
lbl3 = Label(update_opt, text="Old Phone Number: ").grid(row=2,column=1)
pre_phonenumber = Entry(update_opt, textvariable=old_phone, state='readonly')
pre_phonenumber.grid(row=2,column=2)
lbl4 = Label(update_opt, text="New Phone Number: ").grid(row=3,column=1)
new_phonenumber = Entry(update_opt, textvariable=Phone).grid(row=3,column=2)
#New_Number = new_phonenumber.get()
save_btn = ttk.Button(update_opt, text="Save Changes",
command = lambda:save_changes(new_name,old_name,
new_phonenumber,
old_phone))
save_btn.grid(row=4,column=2,sticky=W)
update_opt.mainloop()
def save_changes(new_name, old_name, new_phonenumber, old_phone):
selected_item = tree1.selection()
#gets the values associated with the selected item
values = (tree1.item(selected_item)['values'])
query = 'UPDATE clients SET name=?, phone=? WHERE name=? AND phone=?'
parameters=(new_name, new_phonenumber, old_name, old_phone)
conn = sq.connect('Clients.db')
c3 = conn.cursor()
c3.execute(query, (new_name, new_phonenumber, values,))
conn.commit()
tree1.delete(selected_item)
edit_wind.destroy()
display_clients()
I keep getting this error:
xception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python3.6/tkinter/__init__.py", line 1705, in __call__
return self.func(*args)
File "/home/zizibaby/Desktop/SD Functions .py", line 77, in <lambda>
old_phone))
File "/home/zizibaby/Desktop/SD Functions .py", line 98, in save_changes
c3.execute(query, (new_name, new_phonenumber, values,))
sqlite3.ProgrammingError: Incorrect number of bindings supplied.
The current statement uses 4, and there are 3 supplied.
I added the tree.selection to actually grab the value however it's not working. I tried .get() function but it say NoneType for get().
Please, any help?