I apologize if this is redundant but I can't seem to find the answer.
I've supplied all the values. Still it gives me error that I did not supply value for binding 6. This is My code
def Update_Employee(id,name,phoneno,address,nic,
joindate,email,picture,role,status,
salary,username,password):
with conn:
c.execute("UPDATE Employee "
"SET emp_Name=:emp_name,"
"emp_PhoneNo=:emp_phoneno,"
"emp_Address=:emp_address,"
"emp_NIC=:emp_nic,"
"emp_JoinDate=:emp_joindate,"
"emp_Email=:emp_email"
"emp_Picture=:emp_picture,"
"emp_role=:emp_role,"
"emp_status=:emp_Status,"
"emp_salary=:emp_Salary,"
"emp_Username=:emp_username,"
"emp_Password=:emp_password "
"WHERE emp_ID=:emp_id",
{'emp_id':id,
'emp_name':name,
'emp_phoneno':phoneno,
'emp_address':address,
'emp_nic':nic,
'emp_joindate':joindate,
'emp_email':email,
'emp_picture':picture,
'emp_role':role,
'emp_Status':status,
'emp_Salary':salary,
'emp_username':username,
'emp_password':password})
I've double checked the attributes in my database. Names\spellings are 100% alright and all the values have been suppplied.
Related
I have a file called TBXTools I am trying to run it through another file using
from TBXTools import *
e=TBXTools()
Looks very simple ain't it. But when I run it I get this error:
AttributeError: 'TBXTools' has no attribute 'cur'
Now I have that method, right there on 'TBXTools' file . So what's wrong? Please help
def load_sl_tl_corpus(self,slcorpusfile, tlcorpusfile, encoding="utf-8"):
'''Loads a bilingual corpus in Moses format (that is, in two independent files. It expects one segment per line.'''
self.slcf=codecs.open(slcorpusfile,"r",encoding=encoding)
self.tlcf=codecs.open(tlcorpusfile,"r",encoding=encoding)
self.sl_data=[]
self.tl_data=[]
self.continserts=0
while 1:
self.sl_segment=self.slcf.readline()
if not self.sl_segment:
break
self.tl_segment=self.tlcf.readline()
self.continserts+=1
self.max_id_corpus+=1
self.sl_record=[]
self.tl_record=[]
self.sl_segment=self.sl_segment.rstrip()
self.tl_segment=self.tl_segment.rstrip()
self.sl_record.append(self.max_id_corpus)
self.tl_record.append(self.max_id_corpus)
self.sl_record.append(self.sl_segment)
self.tl_record.append(self.tl_segment)
self.sl_data.append(self.sl_record)
self.tl_data.append(self.tl_record)
if self.continserts==self.maxinserts:
self.cur.executemany("INSERT INTO sl_corpus (id, segment) VALUES (?,?)",self.sl_data)
self.cur.executemany("INSERT INTO tl_corpus (id, segment) VALUES (?,?)",self.tl_data)
self.sl_data=[]
self.tl_data=[]
self.continserts=0
with self.conn:
self.cur.executemany("INSERT INTO sl_corpus (id, segment) VALUES (?,?)",self.sl_data)
self.cur.executemany("INSERT INTO tl_corpus (id, segment) VALUES (?,?)",self.tl_data)
self.conn.commit()
I am calling it like this:
e.load_sl_corpus("Main corpus.txt")
Note: I tried to run it through python -tt but I got the same error
Here are a small sample from my input file:
Clearance returns value as a percent of sales retail amount.
purchase order estimated landed cost each time this item is received at this location, or the primary supplier cost, depending on the merchandising system options.
purchase order estimated landed cost each time this item is received at this location, or the primary supplier cost, depending on the merchandising system options.
Retail value of original planned markdown amounts due to regular sales.
Quantity of unavailable clearance inventory at a location at the beginning of the reporting period, across all inventory status codes.
The percent of demand that flows through to net sales, after accounting for returns and cancellations. Derived as the sum of returns and cancellations divided by demand sales retail value, subtracted from 1 to get the inverse percent value.
#RICP2# - Shrink Non-Clr Cost Amt
Customer Segment Occupation Code
Flexible fact column 31 for text or non-numeric values.
Edit:
I am already create a function to connect my database please have a look below:
def create_project(self,project_name,sl_lang,tl_lang="null",overwrite=False):
'''Opens a project. If the project already exists, it raises an exception. To avoid the exception use overwrite=True. To open existing projects, use the open_project method.'''
if os.path.isfile(project_name) and not overwrite:
raise Exception("This file already exists")
else:
if os.path.isfile(project_name) and overwrite:
os.remove(project_name)
self.sl_lang=sl_lang
self.tl_lang=tl_lang
self.conn=sqlite3.connect(project_name)
self.cur = self.conn.cursor()
self.cur2 = self.conn.cursor()
with self.conn:
self.cur = self.conn.cursor()
You need to initialize the property cur before using it inside constructor.
Please include you __init__() function definition here also.
This question already has answers here:
How do I put a variable’s value inside a string (interpolate it into the string)?
(9 answers)
Python: best practice and securest way to connect to MySQL and execute queries
(2 answers)
Reduce tuple of one item (singleton) to its value
(3 answers)
I'm getting a TypeError. How do I fix it?
(2 answers)
Closed last month.
I have some data that I want to change(unixtime -> human date time).
After then, How can I update result on mysql dynamically.
>>> print data
((1424794931452.0,), (1424794931645.0,), (1424794931821.0,), (1424794932014.0,), (1424794932189.0,)
for i in data:
dt = datetime.fromtimestamp(i[0] // 1000)
s = dt.strftime('%Y-%m-%d %H:%M:%S')
sql2 = "UPDATE accelerometer SET test = "+ s +"WHERE _id="+i
cursor.execute(sql2)
data = cursor.fetchall()
print (s)
this is error message.
TypeError: cannot concatenate 'str' and 'tuple' objects
I want to update those below result data on Mysql dynamically. But have some problem. What is the problem?
2015-02-24 11:22:11
2015-02-24 11:22:11
2015-02-24 11:22:11
2015-02-24 11:22:12
2015-02-24 11:22:12
You are looping over tuples with an id, not a list of ids:
((1424794931452.0,), (1424794931645.0,), (1424794931821.0,), (1424794932014.0,), (1424794932189.0,)
So each i is set to one of those tuples. Extract the id, by using indexing or by adding a comma to the for loop assignment:
for i in data:
dt = datetime.fromtimestamp(i[0] // 1000)
s = dt.strftime('%Y-%m-%d %H:%M:%S')
sql2 = "UPDATE accelerometer SET test = " + s + "WHERE _id=" + i[0]
cursor.execute(sql2)
or
for i, in data:
dt = datetime.fromtimestamp(i // 1000)
s = dt.strftime('%Y-%m-%d %H:%M:%S')
sql2 = "UPDATE accelerometer SET test = " + s + "WHERE _id=" + i
cursor.execute(sql2)
You should really use SQL parameters instead of string concatenation here; you can then reuse the SQL statement:
sql2 = "UPDATE accelerometer SET test = ? WHERE _id=?"
for i, in data:
dt = datetime.fromtimestamp(i // 1000)
cursor.execute(sql2, (i, dt))
where I made two assumptions: that your database driver uses ? as the placeholder syntax (it could be %s instead) and that it natively supports datetime objects (most can these days), so you don't need to use datetime.strftime() to produce a string first.
The statement reuse can go further, in that the database only has to parse the query once, and only has to produce one query plan; this speeds up repeated executions.
Using SQL parameters has another very important advantage: it prevents SQL injection attacks (where an attacker adds quoting and additional SQL statements). For your specific inputs that is not so much of a concern, but should always be kept in mind.
Your core problem is that you're trying to put together a self-sufficient string (with string concatenation in your case, problems with string interpolation are more common, but it's pretty much the same issue).
Rather, use placeholders:
sql2 = "UPDATE accelerometer SET test = %s WHERE _id= %s"
then pass the data to execute:
cursor.execute(sql2, (s, i))
which will do the right thing for you.
It is, of course, possible, though tricky, to build the right stand-alone string -- but it's still very wrong to do so, see https://xkcd.com/327/ and don't expose yourself, ever!, to SQL-injection risks: use placeholders and data in execute, instead!
Your data is stored in tuples. And the error message says that strings and tuples can't be combined as a string, as a tuple isn't a string.
Instead of:
sql2 = "UPDATE accelerometer SET test = "+ s +"WHERE _id="+i
Try:
sql2 = "UPDATE accelerometer SET test = "+ s +"WHERE _id=%f" % i
I wouldn't recommend to use %s to build the string, as that could change the format of your floating point values.
I have the following function in Python:
def get_emo_results(emo, operator):
cursor.execute("SELECT avg(?) FROM [LIWC Post Stats] "
"WHERE goals_scored {0} goals_taken "
"GROUP BY post_number "
"ORDER BY post_number ASC "
"LIMIT ?".format(operator), [emo, posts_limit])
print "SELECT avg({1}) FROM [LIWC Post Stats] "\
"WHERE goals_scored {0} goals_taken "\
"GROUP BY post_number "\
"ORDER BY post_number ASC "\
"LIMIT {2}".format(operator, emo, posts_limit)
return [x[0] for x in cursor.fetchall()]
I call it with get_emo_results('posemo', '>') and get this output to stdout:
SELECT avg(posemo) FROM [LIWC Post Stats] WHERE goals_scored > goals_taken GROUP BY post_number ORDER BY post_number ASC LIMIT 200
However, the function itself returns
[0.0, 0.0, 0.0, 0.0, 0.0, ... 0.0]
I copy and paste that exact expression in stdout to my SQLite process that I have opened, and I get this:
1.8730701754386
2.48962719298246
2.18607456140351
2.15342105263158
2.33107456140351
2.11631578947368
2.37100877192982
1.95228070175439
2.01013157894737
...
3.37183673469388
So not 0 at all. Why does my Python function return something different despite using the same query? What am I doing wrong?
EDIT:
It now works when I get rid of the question marks and format the string directly. Why don't parameterized queries work in this case?
It is being handled differently because you are parametirzing your query. You can't really parameterize a column name like that. It is trying to protect you from SQL injection so it is (I'm simplifying here, but basically) encapsulating any strings in quotes before passing it to the SQL engine.
Essentially, SQLlite is trying to average the string literal 'posemo'
You can keep your limit parameterized, but when it comes to column names you need to have them hardcoded or else put them in the string with something like format.
I have the following code in python. I get this error ->tuple indices must be integers, not str
How can I pass these values into the query? I have other examples where this approach works perfectly, i don't understand why it's failling here.
def request_events_json(uei,interval,conn):
cur = conn.cursor()
events_query ="""select e.nodeid,n.nodelabel,e.ipaddr,count(*) as total,min(e.eventcreatetime),max(e.eventcreatetime),(regexp_matches (e.eventlogmsg,E': %(.*)'))[1] as msglog
from events e, node n where e.eventuei = (%s) and e.eventcreatetime > now() - interval (%s) and n.nodeid=e.nodeid
group by n.nodelabel,e.nodeid,e.ipaddr,msglog
order by e.nodeid, count(*) desc limit 10;"""
try:
print('## Requesting events ##')
cur.execute(events_query,('uei.opennms.org/syslogd/cisco/line','5 min'))
.......
With my version of PostgreSQL the round brackets after interval are forbidden.
Update:
It is the percent-sign in the regexp. Double it.
The problem I have is to identify the type of data entering the database, I think everyone as IntegerField model in Django and Python code only inserts it all in one list and then insert it into the base data.
On the other hand I have no very clear writing Python code length according to the rules of the line, what I do is just see that in the end the code is very long as separated with spaces to align the next line below do not know if this good in this way and that the code will not fail.
The data that has to enter ip_unidad is ('186 .99.41.000 ', 3333) found in' self.addr [0] 'and the data date is '091211' which is in 'self.Cadenapura [17] '
and try "self.Cadenapura [17] = int (self.Cadenapura [17])" but nothing
It records the input data in the database but the two spaces are 0.
any ideas would be grateful.
The console error is:
Warning: Incorrect integer value: 'self.addr[0]' for column 'ip_unidad' at row 1
('self.addr[0]','self.Cadenapura[17]')
Warning:Incorrect integer value: 'self.Cadenapura[17]' for column 'fecha' at row 1
('self.addr[0]','self.Cadenapura[17]')
The code. Py used is:
sql = """INSERT INTO carro ( ip_unidad , hora ) VALUES (%s,%s)"""
db = MySQLdb.Connect(host="localhost", user="root",passwd="--------",db="gprslmgs")
cursor = db.cursor()
try :
cursor.execute(sql,('self.addr[0]','self.Cadenapura[17]'))
db.commit()
except:
db.rollback()
Django model used to create the database is:
class Carro(models.Model):
ip_unidad = models.IntegerField(max_length=15)
fecha = models.IntegerField(max_length=6)
Thank you.
I am not very familiar with Django but what i see is that you specify object within ' - think you don't need to do this. Have you tried something like:
cursor.execute(sql % (self.addr[0], self.Cadenapura[17]))
Or:
cursor.execute(sql, (self.addr[0], self.Cadenapura[17],))
While browsing i found the following MySQLdb sample code:
import MySQLdb
db = MySQLdb.connect(passwd="moonpie",db="thangs")
c = db.cursor()
c.executemany(
"""INSERT INTO breakfast (name, spam, eggs, sausage, price)
VALUES (%s, %s, %s, %s, %s)""",
[
("Spam and Sausage Lover's Plate", 5, 1, 8, 7.95 ),
("Not So Much Spam Plate", 3, 2, 0, 3.95 ),
("Don't Wany ANY SPAM! Plate", 0, 4, 3, 5.95 )
] )
So i think it should work the second way i mentioned.
I see two main problems - first is that '186.99.41.000' is not an integer, this is a string. Django provides an ip address field which is designed for this.
Your second problem is similar to the first, in that '09876' is a string, and your column type is IntegerField, however when you convert '09876' to an integer, you'll get 9876 because in Python, a number starting from 0 is an octal literal:
>>> print 127
127
>>> print 0177
127
>>> print 0x7f
127
So you need to store '09876' as a string in your database, and to do that you need to change your column type to CharField.
Like I said on your newer question, you should use Django's model api to handle the SQL for you.
Carro.objects.create(ip_unidad=self.addr[0], fecha=self.Cadenapura[17])
Furthermore, you should also revise your model. Instead of using IntegerFields, you should instead use
class Carro(models.Model):
ip_unidad = models.IPAddressField()
fecha = models.DateField()
Then when saving your data(with the model's objects.create), you need to make sure that your date is a python datetime.date object. Using the IPAddressField also means that you don't need to bother trying to convert the IP address to an int.