I've got a weird problem. I've made a vba code in excel, that calls a python code that get information from the excel sheet and put it into a database. Yesterday there was no problem. Today I start my computer and tried the vba code and it errors in the python file.
The error:
testchipnr = TC104
Traceback (most recent call last):
testchipID = 108
File "S:/3 - Technical/13 - Reports & Templates/13 - Description/DescriptionToDatabase/DescriptionToDatabase.py", line 40, in <module>
TestchipID = cursorOpenShark.fetchone()[0] # Fetch a single row using fetchone() method and store the result in a variable., the [0] fetches only 1 value
TypeError: 'NoneType' object has no attribute '__getitem__'
The weird thing is that there is a value in the database -> testchipID ...
My code:
#get the testchipID and the testchipname
testchipNr = sheet.cell(7, 0).value # Get the testchipnr
print "testchipnr = ", testchipNr
queryTestchipID = """SELECT testchipid FROM testchip WHERE nr = '%s'""" %(testchipNr)
cursorOpenShark.execute(queryTestchipID)
print "testchipID = ", cursorOpenShark.fetchone()[0]
TestchipID = cursorOpenShark.fetchone()[0] # Fetch a single row using fetchone() method and store the result in a variable., the [0] fetches only 1 value
As you are saying, it was working fine but now it is not, the only reason that I can think of is when your query is returning Zero results.
Looking at your code, if your query is returning only one result, then it will print the result and the next time you are making the call to cursorOpenShark.fetchone() to store in TestchipID it would return None.
Instead, can you try the following code
#get the testchipID and the testchipname
testchipNr = sheet.cell(7, 0).value # Get the testchipnr
print "testchipnr = ", testchipNr
queryTestchipID = """SELECT testchipid FROM testchip WHERE nr = '%s'""" %(testchipNr)
cursorOpenShark.execute(queryTestchipID)
TestchipID = cursorOpenShark.fetchone()[0] # Fetch a single row using fetchone() method and store the result in a variable., the [0] fetches only 1 value
if TestchipID:
print "testchipID = ", TestchipID[0]
else:
print "Returned nothing"
Let me know if this works.
Related
I'm trying to create a simple script for changing some mysql data, but I'm little bit confused about parametrized queries. The code look like this:
reader_id = sys.argv[1]
cmd_id = sys.argv[2]
conn = mysql.connect(user='...', passwd='...', host='...', db='...')
curs = conn.cursor()
mysql_data = {
"reader_id": int(reader_id),
"cmd_id": int(cmd_id)
}
curs.execute("UPDATE `reader_config_hw` SET `changed_` = '1' "
"WHERE `object_id` = %(reader_id)d AND `id` = %(cmd_id)d;", mysql_data)
curs.execute("UPDATE `reader` SET `check_for_command` = '1' WHERE `id` = %(reader_id)d", mysql_data)
and the error result is
Traceback (most recent call last):
File "./main.py", line 25, in <module>
"WHERE `object_id` = %(reader_id)d AND `id` = %(cmd_id)d;", mysql_data)
File "/usr/lib64/python3.6/site-packages/MySQLdb/cursors.py", line 210, in execute
query = query % args
TypeError: %d format: a number is required, not str
It says that number is required but I already changed the type of the variable by int(reader_id), is it right?
Try changing
"WHERE 'object_id' = %(reader_id)d AND 'id' = %(cmd_id)d;"
to
"WHERE 'object_id' = %(reader_id)s AND 'id' = %(cmd_id)s;"
I think the 'd' after your variable calls indicates a "digit" whereas you need to use a string.
EDIT: to clarify, strings can be used in place of integers in MySQL queries
Im having a problem inserting a variable into sqlite3 and the variable is hashed.
Here's my code:
if passadefinir == passadefinir2:
maindb.execute("DELETE FROM Password WHERE ID = 'not'")
maindb.execute("INSERT INTO Password(ID) VALUES ('set')")
encriptacao = hashlib.sha1(passadefinir2.encode())
encriptado = (encriptacao.hexdigest(),)
maindb.execute("INSERT INTO Password(Password) VALUES (?)" (encriptado,))
conn.commit()
Here's the error:
Traceback (most recent call last):
File "sqlitetesting.py", line 28, in
maindb.execute("INSERT INTO Password(Password) VALUES (?)" (encriptado,))
TypeError: 'str' object is not callable
Have a nice day :D,
Luis Duarte.
You can substitute using String's format method
password_var = 'your password'
insert_statement = 'INSERT INTO Password(Password) VALUES ({0})'.format('\'' + password_var + '\'')
then run the execute method as:
maindb.execute(insert_statement)
I'm trying to tally the number of instances of a top level domain occur in a file containing 800K+ top level domain strings that I scraped from URLs. In the code below, when I used "if mstlds in ntld:" the results appeared to be correct but upon inspection "co" and "com", "ca" and "cat" counts are incorrect. But if I use == or "is" I don't get any matches at all but instead an error:
Traceback (most recent call last):
File "checktlds4malware.py", line 111, in
mtlds_line = mtlds.readline()
AttributeError: 'str' object has no attribute 'readline'
tld_file = open(sys.argv[1],'r')
tld_line = tld_file.readline()
while tld_line:
#print(tld_line)
tld_line = tld_line.strip()
columns = tld_line.split()
ntld = columns[0] # get the ICANN TLD
ntld = ntld.lower()
mtlds = open ('malwaretlds.txt', 'r')
mtlds_line = mtlds.readline()
while mtlds_line:
print(mtlds_line)
mtlds_line = mtlds_line.strip()
columns = mtlds_line.split()
mtlds = columns[0]
mtlds = mtlds.lower()
#raw_input()
# I don't get the error when using "in" not ==
# but the comparison is not correct.
if mtlds_line == ntld:
m_count += 1
print 'ntld and mtld match: Malware domain count for ', ntld, m_count
mtlds_line = mtlds.readline()
print 'Final malware domain count for ', ntld, m_count
This is because within your while loop, you are setting mtlds to be a String. Thus, once you attempt to use the readline() method you throw the error (pretty self explanatory). You have to remember that only outside the scope of your interior while loop is mtlds pointing to a file.
So basically, I have an api from which i have several dictionaries/arrays. (http://dev.c0l.in:5984/income_statements/_all_docs)
When getting the financial information for each company from the api (e.g. sector = technology and statement = income) python is supposed to return 614 technology companies, however i get this error:
Traceback (most recent call last):
File "C:\Users\samuel\Desktop\Python Project\Mastercopy.py", line 83, in <module>
user_input1()
File "C:\Users\samuel\Desktop\Python Project\Mastercopy.py", line 75, in user_input1
income_statement_fn()
File "C:\Users\samuel\Desktop\Python Project\Mastercopy.py", line 51, in income_statement_fn
if is_response ['sector'] == user_input3:
KeyError: 'sector'
on a random company (usually on one of the 550-600th ones)
Here is the function for income statements
def income_statement_fn():
user_input3 = raw_input("Which sector would you like to iterate through in Income Statement?: ")
print 'Starting...'
for item in income_response['rows']:
is_url = "http://dev.c0l.in:5984/income_statements/" + item['id']
is_request = urllib2.urlopen(is_url).read()
is_response = json.loads(is_request)
if is_response ['sector'] == user_input3:
csv.writerow([
is_response['company']['name'],
is_response['company']['sales'],
is_response['company']['opening_stock'],
is_response['company']['purchases'],
is_response['company']['closing_stock'],
is_response['company']['expenses'],
is_response['company']['interest_payable'],
is_response['company']['interest_receivable']])
print 'loading...'
print 'done!'
print end - start
Any idea what could be causing this error?
(I don't believe that it is the api itself)
Cheers
Well, on testing the url you pass in the urlopen call, with a random number, I got this:
{"error":"not_found","reason":"missing"}
In that case, your function will return exactly the error you get. If you want your program to handle the error nicely and add a "missing" line instead of actual data, you could do that for instance:
def income_statement_fn():
user_input3 = raw_input("Which sector would you like to iterate through in Income Statement?: ")
print 'Starting...'
for item in income_response['rows']:
is_url = "http://dev.c0l.in:5984/income_statements/" + item['id']
is_request = urllib2.urlopen(is_url).read()
is_response = json.loads(is_request)
if is_response.get('sector', False) == user_input3:
csv.writerow([
is_response['company']['name'],
is_response['company']['sales'],
is_response['company']['opening_stock'],
is_response['company']['purchases'],
is_response['company']['closing_stock'],
is_response['company']['expenses'],
is_response['company']['interest_payable'],
is_response['company']['interest_receivable']])
print 'loading...'
else:
csv.writerow(['missing data'])
print 'done!'
print end - start
The problem seems to be with the final row of your income_response data
{"id":"_design/auth","key":"_design/auth","value":{"rev":"1-3d8f282ec7c26779194caf1d62114dc7"}}
This does not have a sector value. You need to alter your code to handle this line, for example by ignoring any line where the sector key is not present.
You could easily have debugged this with a few print statements - for example insert
print item['id'], is_response.get('sector', None)
into your code before the part that outputs the CSV.
A KeyError means that the key you tried to use does not exist in the dictionary. When checking for a key, it is much safer to use .get(). So you would replace this line:
if is_response['sector'] == user_input3:
With this:
if is_response.get('sector') == user_input3:
I have a problem with a Python 2.7 project.
I'm trying to set a variable to a value retrieved from an sqlite3 database, but I'm having trouble. Here is my code thus far, and the error I'm receiving. Yes, the connection opens just fine, and the table, columns, and indicated row are there as they should be.
import sqlite3 import Trailcrest
conn = sqlite3.connect('roster.paw')
c = conn.cursor()
def Lantern(AI):
"""Pulls all of the data for the selected user."""
Trailcrest.FireAutoHelp = c.execute("""select fireautohelp
from roster
where index = ?;""", (AI,) ).fetchall()
The error is:
> Traceback (most recent call last):
> File "<pyshell#4>", line 1, in <module> Lantern(1)
> File "C:\Users\user\MousePaw Games\Word4Word\PYM\Glyph.py", line 20,
> in Lantern
> Trailcrest.FireAutoHelp = c.execute("""select fireautohelp from roster where index = ?;""", (AI,)).fetchall()
> OperationalError: near "index": syntax error
As Thomas K mentions in a comment, index is a SQL keyword.
You can either rename that column, or enclose in backticks:
Trailcrest.FireAutoHelp = c.execute("""select fireautohelp
from roster
where `index` = ?;""", (AI,) ).fetchall()