I have a table in postgresql where initially the table will be empty not as null value it will be empty
i am running a select query which will display the value as empty, but i need it to return null
this is my query
select job_status,refreshed_properties,total_number_of_properties_to_be_refreshed
from job_table
this is my python code
check_job_status = """select job_status,refreshed_properties,total_number_of_properties_to_be_refreshed
from job_table"""
cursor.execute(check_job_status)
job_status = cursor.fetchall()
print (job_status)
print("the above result is the job status ")
either i need to handle it in postgresql or need to handle in python
table structure
python output
Use nulliff():
select
nullif(job_status, '') as status,
refreshed_properties,
total_number_of_properties_to_be_refreshed
from job_table
If job_status is equal to the empty string, this returns a null value instead.
i am running a select query which will display the value as empty, but i need it to return null
I think you want to return None and not null. Isnt it?
Just check if the list is empty and print None if it is.
job_status = cursor.fetchall()
print (job_status if len(job_status) else None)
print("the above result is the job status ")
Related
I have this little code
cquery = "SELECT * FROM `workers` WHERE `Username` = (%s)"
cvalue = (usernameR,)
flash(cquery)
flash(cvalue)
x = c1.execute(cquery, cvalue)
flash(x)
usernameR is a string variable I got it's value from a form
x supposed to be the number of rows or some value but it returns none I need it's value for one if.
I tested it with a value that is in the table in one row so thats not the case the the value is not there or something. But if it's not there in that case the x should return 0 or something.
I cant work out what's the problem after several hours.
value of cvalue:
('Csabatron99',)
Edit for solution:
I needed to add the rowcount and fetchall to the code like this:
cquery = "SELECT * FROM `workers` WHERE `Username` = (%s)"
cvalue = (usernameR,)
flash(cquery)
flash(cvalue)
c1.execute(cquery, cvalue)
c1.fetchall()
a = c1.rowcount
cursor.execute() doesn't return anything in the normal case. If you use the multi=True argument, it returns an iterator used to get results from each of the multiple queries.
To get the number of rows returned by the query, use the rowcount attribute.
c1.execute(cquery, cvalue)
flash(c1.rowcount)
I'm new to Python and was working on a script which executes a postgres query and pulls its result, it's just a number:
con = psycopg2.connect("dbname=mydb user=postgres host=192.168.0.10")
cur = con.cursor()
myvar='TEST'
cur.execute("SELECT get_id('myvar')")
my_id = cur.fetchone()
print(my_id)
The results I get are like these depending on the myvar value:
(144,)
(140,)
(141,)
Sometimes when there's no value returned by the query, I get this:
(None,)
I was expecting something like "null" (similar to what I get when I run this on the DB) but that wasn't the case.
Question number one is: why do I get the values surrounded by a parenthesis and the comma at the end?
Question two is: How "if" may work when the value is 'None'?
I've tried this:
if my_id=='None':
if my_id=='(None,)':
but didn't work..
The result is a tuple, which is an immutable sequence
Check if the first item of the tuple is None:
if my_id[0] is None:
pass
Also, please be sure that you are using the proper string substitution with psycopg2. Your code should look something like this:
con = psycopg2.connect("dbname=mydb user=postgres host=192.168.0.10")
cur = con.cursor()
myvar='TEST'
cur.execute("SELECT get_id(%s)", [myvar])
my_id = cur.fetchone()[0]
if my_id is not None:
print(my_id)
In my code I have a function that needs to return either a string or None depending on what is present in the database. However at the moment the result is a list with the string answer inside, or None. Is there any change that could be made that would result in just a string or None being returned, rather than having to index the list?
Here is the code:
def retrieve_player_name(username):
param = [(username)]
command = ("""
SELECT username FROM players
WHERE username = ?
""")
result = cur.execute(command, param).fetchone()
if result is not None:
return result[0]
Thanks in advance.
A database cursors fetches entire rows, not values.
Even a row with a single value inside is still a row.
If you don't want to write row[0] multiple times, create a helper function execute_and_return_a_single_value_from_query().
title = article.title
title = re.sub(r' - Wikipedia, the free encyclopedia','',title)
title_lower = title.lower()
title_lower = title_lower.replace(' ','-')
print title
print title_lower
title_query = ("INSERT INTO myguests "
"(firstname) "
"VALUES (%s)")
cursor.execute("SELECT id FROM myguests "
"WHERE firstname='"+title+"'")
row = cursor.fetchall()
if row !=[]:
print "List is not empty"
if not row:
print "List is empty"
title_query = title
print title
For some reason in my if statement my title variable keeps coming back empty when it is called if not row:
I am trying to insert variable if the variable dose not exist in column.
If no rows are returned then it's probably because there is no data in the table with the requested firstname. Try adding some debugging to your code and use a parameterised query rather than string concatenation:
cursor.execute("SELECT id FROM myguests WHERE firstname = %s", (title,))
row = cursor.fetchall()
print 'Got row: {!r}'.format(row) # some debugging
if row:
print "Record for {} already exists".format(title)
else:
print "List is empty, attempting to insert"
cursor.execute(title_query, (title,))
But there is a potential race condition with this approach; what if some other process adds the value to the database between the initial check and the subsequent insert? Depending on your application this may or may not be a problem.
Regarding "insert if not exists", one way is to set a UNIQUE INDEX on the firstname column. and then simply attempt to insert a new row without checking first. If a row exists with the same value for firstname the insert will fail. If no such row exists, the insert will be attempted (it might still fail, but for other reasons). Your code needs to handle insertion failure due to duplicate key.
Or you could investigate use of INSERT IGNORE into myguests ..., or some of the other options discussed here: How to 'insert if not exists' in MySQL?.
But are you really sure that firstname should be unique? It seems to me likely that many guests could have the same first name.
I am playing with python for the first time on the raspberry pi.
I have a script that queries an SQL table and returns the value that is set.
What I can not get to work is setting the python variable from the results.
Here is part of the code I have
# execute SQL query using execute() method.
cursor.execute("select id from wallboard")
# Fetch a single row using fetchone() method.
data = cursor.fetchone()
# disconnect from server
db.close()
result = str("%s " % data)
print result
if result == 1:
The print displays the result okay but it is not going into the if statement.
I am very new to python so its possibly a simple fix but I'm stumped.
Thanks
Don't convert the result to string:
>>> "1" == 1
False
Also note that fetchone() would return you a single row of results which would be represented as a tuple - get the first item to get the actual id column value:
result = cursor.fetchone()[0]