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().
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 want to display a data in QTableWidget according to QComboBoxes. In case of select all gender or select all ages, I want apply select all in the column in sqlite3 query
I want gender to be all
gender = "select all both male and female"
connection.execute("SELECT * FROM child where region=? and hospital=? and ageInMonths=? and gender=?", (region,hospital,ageInMonths,gender))
Welcome to Stackoverflow.
While it's a little tedious, the most sensible way to attack this problem is to build a list of the conditions you want to apply, and another of the data values that need to be inserted. Something like the following (untested) code, in which I assume that the variables are set to None if they aren't required in the search.
conditions = []
values = []
if region is not None:
conditions.append('region=?')
values.append(region)
# And similar logic for each other value ...
if gender is not None:
conditions.append('gender=?')
values.append(gender)
query = 'SELECT * FROM child'
if conditions:
query = query + ' WHERE ' + ' AND '.join(conditions)
connection.execute(query, values)
This way, if you want to include all values of a column you simply exclude if from the conditions by setting it to None.
You can build your where clause and your parameter list conditionally.
Below I am assuming that the ageInMonths and gender variables actually contain the value 'all' when this is selected on your form. You can change this to whichever value is actually passed to your code, if it is something different.
When it comes to your actual query, the best way to get all values for a field is to simply exclude it from the where clause of your query entirely.
So something like:
query_parameters = []
query_string = "SELECT * FROM child where region=? and hospital=?"
query_parameters.append(region)
query_parameters.append(hospital)
if ageInMonths != 'all':
query_string += " and ageInMonths=?"
query_parameters.append(ageInMonths)
if gender != 'all':
query_string += " and gender=?"
query_parameters.append(gender)
connection.execute(query_string, query_parameters)
Basically, at the same time we are testing and building the dynamic parts of the SQL statement (in query_string), we are also dynamically defining the list of variables to pass to the query in query_parameters, which is a list object.
def check_gen0_1(db_name):
with sqlite3.connect(db_name) as db:
cursor = db.cursor()
cursor.execute("select JuvPop from History where Generation=0")
global results1
results1 = cursor.fetchone()
def check_gen0_run(db_name):
if __name__ == "__main__":
check_gen0_1(db_name)
def menu2(dbless, db_name):
check_gen0_run(db_name)
print(results1)
This is my code. The result printed is
(0,)
How do I get rid of the brackets? How do I only get the 0 or whatever value is there.
.fetchone() returns a single row of results of the query which is represented as a tuple. If you need the first value from it, just get it by index:
print(results1[0])
Not sure if:
results1 = results1[1:-2]
print(results1)
or just:
print(results1[1:-2])
would get you what you wanted? Depends if the output you're getting is a string of course.
This splits the first char and last 2 characters from the results, which is fine if this is something that will happen for every value you're getting but will cause issues if these values are changeable.
I am trying to perform a query which returns back a document each time. The problem is that some docs have multiple instances in the database. So instead of getting one doc with a query I am getting multiple results. Thus I am trying to use find_one method which return the first query match. However, changing from find to find_one method I am facing a new problem. My code is the following:
lines = [line.rstrip() for line in open('ids.txt')]
list_names = []
names= open('name.txt', 'w')
for x in range(0,3000):
id = int(lines[x])
print x ,' ',lines[x]
for cursor in collection.find_one({"_id.uid": id}):
name = cursor['screenname']
print name
list_names.append(name)
names.write("%s\n" % name)
names.close()
I have a list of ids and I want to return the correspondant names from mongoDb. However, I am getting `name = cursor['screenname']
TypeError: string indices must be integers
What am I doing wrong here?
The find_one method does not return a cursor. It returns the document itself.
session = self.sessions.find_one({'_id': session_id})
print session # must print your document
I'm making a search function for my website that breaks the entered text by spaces and then checks each work with __contains. I want to expand this so that I can pass through what columns I want it to check __contains with such as "First name", "Last Name"... ect.
What I have now:
def getSearchQuery(search,list,columns=None):
"""
Breaks up the search string and makes a query list
Filters the given list based on the query list
"""
if not columns:
columns = { name }
search = search.strip('\'"').split(" ")
for col in columns:
queries = [Q(col__contains=value) for value in search]
query = queries.pop()
for item in queries:
query |= item
return list.filter(query)
Issue is Q(col__contains=value) doesnt work as "col" is not a column. Is there some way to tell django that that is a variable and not the actual column? I have tried googling this but honestly dont know how to phrase it without putting all my code.
Do it this way:
import operator
from functools import reduce
def getSearchQuery(search, list, columns=None):
"""
Breaks up the search string and makes a query list
Filters the given list based on the query list
"""
if not columns:
return list
search = search.strip('\'"').split(" ")
queries = []
for col in columns:
queries.extend([Q((col+'__icontains', value)) for value in search])
return list.filter(reduce(operator.or_, queries))