cursor.fetchall() throws index out or range error - python-3.6

I have an issue which I am not sure where the root cause is:
I use python cx_Oracle to connect to an Oracle DB.
cursor.fetchall() returns me records in this format [(4352,)]
I want to retrieve the '4352' so i proceed to do this: pk = cursor.fetchall()[0][0]
However i get: IndexError: list index out of range
I am not sure what I am doing wrong since when i manually create this return object on my python console as such: item = [(4352,)], I can retrieve the '4352' by calling item[0][0]
Thanks

I figured out what went wrong.
In my code i did something like this:
print(cursor.fetchall()) # line 56
a = cursor.fetchall()[0][0] # line 57
At line 56, the output of [(4352,)] is correct.
However at line 57, the cursor.fetchall() becomes a []. This is because cursor.fetchall() is a generator. It has been automatically garbage-collected after line 56.
Therefore, if I wanted to extract out 4352 from the inner tuple, I had to call line 57 first and subsequently print(a) if I wanted to see the value of the return result from the database.

Are you sure about the list returned by the fetchall() statement?
It looks like the resulting list is empty.

Related

Make SQLite abort on first error (and sing songs)

I wanted to name this post Make SQLite abort on first error but StackOverflow's AI overlords decided it doesn't fit their conception of intelligent human behavior. For the record, I was googling exactly that, but perhaps even Google AI considered my question unworthy and didn't bother to help me. Mods, feel free to change the title according to what your AI bosses desire (if you can figure it out).
I have this script
create if not exists table entries (
id integer primary key,
start datetime not null,
end datetime not null
);
delete from entries;
insert into entries values (1, '2018-08-01 10:00', '2018-08-01 15:00');
insert into entries values (2, '2018-08-01 17:00', '2018-08-01 20:00');
insert into entries values (1, '2018-08-02 19:00', '2018-08-02 00:00');
insert into entries values (1, '2018-08-03 00:00', '2018-08-03 04:00');
insert into entries values (1, '2018-08-03 14:00', '2018-08-03 18:00');
There is a mistake in create statement. When I run the script I get
% sqlite3 db.sqlite3 <ddl.sql
Error: near line 1: near "if": syntax error
Error: near line 7: no such table: entries
Error: near line 8: no such table: entries
Error: near line 9: no such table: entries
Error: near line 10: no such table: entries
Error: near line 11: no such table: entries
Error: near line 12: no such table: entries
How do I make SQLite exit executing the script on first error it encounters? I'm looking for equivalent of set -e in Bash.
From the documentation, it looks like you can turn on the dot command .bail.
.bail on|off Stop after hitting an error. Default OFF
See also - O'Reilly Using Sqlite
Edit
To exit, you can use the .exit dot command.

print function returning syntax error when used in Python3.6 IDLE (on MacOS)

I have a text file that contains some basic passwords and some variants of those basic passwords. They are typed out together like this:
qwerty, qwerty1
password, password1
default, default 1
123, 12345, 123456
I am trying to take these values and split them, storing them in a tuple and then print out the values as 'Password' and then any variants, but I am getting a syntax error on the print BIF? (I am aware this will not print out the password '123456', I am just trying to solve the syntax error first.)
for each_line in passwords:
(passwd, passwd_variant) = each_line.split(',',1)
print(f'Password: {passwd}, Variant {passwd_variant}')
SyntaxError: invalid syntax
normally if I was writing a script, in the editor I would put print on a new line, however a new line in IDLE simply executes the code above it. is there a shortcut or something to do a carriage return and write the print statement on a new line and if so, is that the cause of the syntax error and why?
Cheers
EDIT: I would like my output to be this
Finally discovered that you need to hit Enter after the for in statement, this will then take you to a new line inside for in statement. Was up all night trying to work it out, maybe my fresh brain helped this morning.

Query range not equal to zero

I'm in AX 2012 R2 environment.
I would like to add a query range to HcmEmployment table and filter out rows that have a LegalEntity value = 0.
The following code fails at runtime with the exception "Invalid Range".
qbrLegalEntity = qbds.addRange(fieldNum(HcmEmployment, LegalEntity));
strRangeCondition = '(%1 != %2)';
qbrLegalEntity.value(strFmt(strRangeCondition,
fieldStr(HcmEmployment, LegalEntity),
queryValue("0")));
Is it possible to code this range condition?
Thank you.
Do not make it harder:
qbds.addRange(fieldNum(HcmEmployment,LegalEntity)).value(SysQuery::valueNot(0));
The reason for your failed query expression was the use of queryValue("0") which quotes the zero. Changing that to 0 would work as well, but again too laborious.
And even shorter is:
qbds.addRange(fieldNum(HcmEmployment,LegalEntity)).value('!0');
To diagnose query errors take a look on the SQL generated:
info(qbds.toString());

How to get programatically the file path from a directory parameter in abap?

The transaction AL11 returns a mapping of "directory parameters" to file paths on the application server AFAIK.
The trouble with transaction AL11 is that its program only calls c modules, there's almost no trace of select statements or function calls to analize there.
I want the ability to do this dynamically, in my code, like for instance a function module that took "DATA_DIR" as input and "E:\usr\sap\IDS\DVEBMGS00\data" as output.
This thread is about a similar topic, but it doesn't help.
Some other guy has the same problem, and he explains it quite well here.
I strongly suspect that the only way to get these values is through the kernel directly. some of them can vary depending on the application server, so you probably won't be able to find them in the database. You could try this:
TYPE-POOLS abap.
TYPES: BEGIN OF t_directory,
log_name TYPE dirprofilenames,
phys_path TYPE dirname_al11,
END OF t_directory.
DATA: lt_int_list TYPE TABLE OF abaplist,
lt_string_list TYPE list_string_table,
lt_directories TYPE TABLE OF t_directory,
ls_directory TYPE t_directory.
FIELD-SYMBOLS: <l_line> TYPE string.
START-OF-SELECTION-OR-FORM-OR-METHOD-OR-WHATEVER.
* get the output of the program as string table
SUBMIT rswatch0 EXPORTING LIST TO MEMORY AND RETURN.
CALL FUNCTION 'LIST_FROM_MEMORY'
TABLES
listobject = lt_int_list.
CALL FUNCTION 'LIST_TO_ASCI'
EXPORTING
with_line_break = abap_true
IMPORTING
list_string_ascii = lt_string_list
TABLES
listobject = lt_int_list.
* remove the separators and the two header lines
DELETE lt_string_list WHERE table_line CO '-'.
DELETE lt_string_list INDEX 1.
DELETE lt_string_list INDEX 1.
* parse the individual lines
LOOP AT lt_string_list ASSIGNING <l_line>.
* If you're on a newer system, you can do this in a more elegant way using regular expressions
CONDENSE <l_line>.
SHIFT <l_line> LEFT DELETING LEADING '|'.
SHIFT <l_line> RIGHT DELETING TRAILING '|'.
SPLIT <l_line>+1 AT '|' INTO ls_directory-log_name ls_directory-phys_path.
APPEND ls_directory TO lt_directories.
ENDLOOP.
Try the following
data : dirname type DIRNAME_AL11.
CALL 'C_SAPGPARAM' ID 'NAME' FIELD 'DIR_DATA'
ID 'VALUE' FIELD dirname.
Alternatively if you wanted to use your own parameters(AL11->configure) then read these out of table user_dir.

Lua: Doing arithmetic in for k,v in pairs(tbl) loops

I have a table such as the following:
mafiadb:{"Etzli":{"alive":50,"mafia":60,"vigilante":3,"doctor":4,"citizen":78,"police":40},"Charneus":{"alive":29,"mafia":42,"vigilante":6,"doctor":14,"citizen":53,"police":33}}
There are more nested tables, but I'm just trying to keep it simple for now.
I run the following code to extract certain values (I'm making an ordered list based on those values):
sortmaf={}
for k,v in pairs(mafiadb) do
sortmaf[k]=v["mafia"]
end
That's one of the codes I run. The problem I'm running into is that it doesn't appear you can do arithmetic in a table loop. I tried:
sortpct={}
for k,v in pairs(mafiadb) do
sortpct[k]=(v["alive"]*100)/(v["mafia"]+v["vigilante"]+v["doctor"]+v["citizen"]+v["police"])
end
It returns that I'm attempting to do arithmetic on field "alive." What am I missing here? As usual, I appreciate any consideration in answering this question!
Editing:
Instead of commenting on the comment, I'm going to add additional information here.
The mafiadb database I've posted IS the real database. It's just stripped down to two players instead of the current 150+ players I have listed in it. It's simply structured as such:
mafiadb = {
Playername = {
alive = 0
mafia = 0
vigilante = 0
doctor = 0
police = 0
citizen = 0
}
}
Add a few hundred more playernames, and there you have it.
As for the error message, the exact message is:
attempt to perform arithmetic on field 'alive' (nil value)
So... I'm not sure what the problem is. In my first code, the one with sortmaf, it works perfectly, but suddenly, it can't find v["alive"] as a value when I'm trying to do arithmetic? If I just put v["alive"] by itself, it's suddenly found and isn't nil any longer. I hope this clarifies a bit more.
This looks like a simple typo to me.
Some of your 150 characters is not well written - probably they don't have an "alive" property, or it's written incorrectly, or it's not a number. Try this:
for k,v in pairs(mafiadb) do
if type(v.alive) ~= 'number' then
print(k, "doesn't have a correct alive property")
end
end
This should print the names of the "bad" characters.

Resources