retrieve equal value from mysql - python

In my code, when the raw_input is equal, it must print the respective single value, but here I get both the values.
If I type raw_input is bike, it displays both bike and car, instead of only bike
Please help, me to get only the one value
Database:
bike
car
coding:
import MySQLdb
db = MySQLdb.connect(host="localhost", # your host, usually localhost
user="root", # your username
passwd="mysql", # your password
db="sakila") # name of the data base
cursor = db.cursor()
# execute SQL select statement
cursor.execute("SELECT A1 FROM adarsh1")
name = raw_input("What's your name? ")
keywords1=[]
for i in cursor.fetchall():
keywords1.append(i[0])
if name in keywords1:
print i[0]

for i in cursor.fetchall():
keywords1.append(i[0])
if name == i[0]:
print i[0]
# Do whatever other things are being done in this loop
The condition on which you were outputing the database value in your posted code (checking if name is in keywords1) will cause that print statement to run for every database value inclusively after the one that matched the user's input. From your question, you only want the print statement to execute once, and never again.

This seems like problem with your indentation. Your if condition should be outside your for loop. (So when inside the for loop, IF condition check will happen for n number of time where n equals to number of rows in your table).
But why complicating this code. You can easily achieve this using your sql query itself.
name = raw_input("What's your name? ")
cursor.execute("SELECT A1 FROM adarsh1 where A1 = '%s'"%name)
cursor.fetchall() # will have your filtered result.

Related

how to make a list out of oracle query output

i am trying to make a list out of the oracle query output. The list would further be used to plot the graph.
I am unable to make a clean list out of the query output. Please suggest.
"""
Created on Sat Sep 21 11:36:10 2019
#author: Pitanshu
"""
# import modules
import cx_Oracle
# database connection
user=input('Enter the user for database : ')
passwd=input('enter the password for the above user : ')
conn_str=user+'/'+passwd+'#localhost/orcl'
conn=cx_Oracle.connect(conn_str)
# creation of cursor
cursor=conn.cursor()
cur=cursor.execute('select distinct emp_name from employee')
employee=[]
col_names = [row[0] for row in cursor.description]
print(col_names)
for i in cur:
employee.append(i)
print(employee)
#closing cursor and connection
cursor.close()
conn.close()
output received:
Enter the user for database : system
enter the password for the above user : ********
['EMP_NAME']
[('e',), ('d',), ('a',), ('b',), ('c',)]
output expected:
Enter the user for database : system
enter the password for the above user : ********
['EMP_NAME']
['e','d','a','b','c']
Just change the equivalent lines to:
for i in cur:
employee.append(i[0]) #for python newbies, getting the only element in the list could also be done with: i[-1] or next(iter(i)) or operator.itemgetter(0)(i) or operator.itemgetter(-1)(i) or i.pop() or i.pop(0) or i.pop(-1)
The logic behind it is:
When querying a relational database table, you're getting rows (in the form of lists in this case) in return. So even if you want just one column per row, you'll get a list per row with one element in it rather than the element itself.
As a naming convention, you might want to go with employees rather than employee when naming a list.

Retrieve data from sql database using python

I'm a newbie for python and SQL.
My database contain a field which stored path to images.
I want to assign each path to a variable in python.
I can only store only the path of first row.
This is my code
import pymysql
from arcpy import env
env.workspace = "D:/year 4 semester 1/Python/Data/"
conn= pymysql.connect(host='localhost',user='root',password='',db='research')
cursor = conn.cursor ()
cursor.execute ("select Path from sourcedata")
data = cursor.fetchmany()
for row in data :
a= row[0]
print a
But when I try following way including all other relevant text
for row in data :
a= row[0]
b = row[1]
c = row[2]
print a
Following error appear
IndexError: tuple index out of range
you need to indent the print a statement to make it part of the loop. Python is very sensitive about indentation. In other languages you use braces or BEGIN END blocks, but in python you use indentation.
The row[0], row[1] stuff refers to the elements within the retrieved row, not the different rows.
indent the print line and it will print the first returned field, Path, for each record.
The tuple index is out of range because there is only one field (element zero) returned.
Your current code will iterate through every row returned and set a to each one in turn, but will only print the last value for a after it comes out of the loop.

Set python variable from result of SQL query

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]

How can I insert a Python variable in a sqlite query?

I'm looking for the way to be able to compare what is in a Python variable with something in a SQLite query.
For example:
num = input ("enter a number")
cur.execute("SELECT a.Name,a.Number FROM Ads a WHERE a.Number = (num)")
row = cur.fetchone()
while row:
print(row)
row = cur.fetchone()
The cur.execute line doesn't work. I don't know how to be able to compare content of a Python variable with data in a SQLite database via a SQlite query.
You put a '?' as a place holder for each Python variable, something like
num = 5
cur.execute("SELECT Name, Number FROM Ads WHERE Number = ?", (num,))
The execute() method expects a sequence as a second argument, since several '?' positional placeholders can be used in the SQL statement.

How to get the numbers of data rows from sqlite table in python

I am trying to get the numbers of rows returned from an sqlite3 database in python but it seems the feature isn't available:
Think of php mysqli_num_rows() in mysql
Although I devised a means but it is a awkward: assuming a class execute sql and give me the results:
# Query Execution returning a result
data = sql.sqlExec("select * from user")
# run another query for number of row checking, not very good workaround
dataCopy = sql.sqlExec("select * from user")
# Try to cast dataCopy to list and get the length, I did this because i notice as soon
# as I perform any action of the data, data becomes null
# This is not too good as someone else can perform another transaction on the database
# In the nick of time
if len(list(dataCopy)) :
for m in data :
print("Name = {}, Password = {}".format(m["username"], m["password"]));
else :
print("Query return nothing")
Is there a function or property that can do this without stress.
Normally, cursor.rowcount would give you the number of results of a query.
However, for SQLite, that property is often set to -1 due to the nature of how SQLite produces results. Short of a COUNT() query first you often won't know the number of results returned.
This is because SQLite produces rows as it finds them in the database, and won't itself know how many rows are produced until the end of the database is reached.
From the documentation of cursor.rowcount:
Although the Cursor class of the sqlite3 module implements this attribute, the database engine’s own support for the determination of “rows affected”/”rows selected” is quirky.
For executemany() statements, the number of modifications are summed up into rowcount.
As required by the Python DB API Spec, the rowcount attribute “is -1 in case no executeXX() has been performed on the cursor or the rowcount of the last operation is not determinable by the interface”. This includes SELECT statements because we cannot determine the number of rows a query produced until all rows were fetched.
Emphasis mine.
For your specific query, you can add a sub-select to add a column:
data = sql.sqlExec("select (select count() from user) as count, * from user")
This is not all that efficient for large tables, however.
If all you need is one row, use cursor.fetchone() instead:
cursor.execute('SELECT * FROM user WHERE userid=?', (userid,))
row = cursor.fetchone()
if row is None:
raise ValueError('No such user found')
result = "Name = {}, Password = {}".format(row["username"], row["password"])
import sqlite3
conn = sqlite3.connect(path/to/db)
cursor = conn.cursor()
cursor.execute("select * from user")
results = cursor.fetchall()
print len(results)
len(results) is just what you want
Use following:
dataCopy = sql.sqlExec("select count(*) from user")
values = dataCopy.fetchone()
print values[0]
When you just want an estimate beforehand, then simple use COUNT():
n_estimate = cursor.execute("SELECT COUNT() FROM user").fetchone()[0]
To get the exact number before fetching, use a locked "Read transaction", during which the table won't be changed from outside, like this:
cursor.execute("BEGIN") # start transaction
n = cursor.execute("SELECT COUNT() FROM user").fetchone()[0]
# if n > big: be_prepared()
allrows=cursor.execute("SELECT * FROM user").fetchall()
cursor.connection.commit() # end transaction
assert n == len(allrows)
Note: A normal SELECT also locks - but just until it itself is completely fetched or the cursor closes or commit() / END or other actions implicitely end the transaction ...
I've found the select statement with count() to be slow on a very large DB. Moreover, using fetch all() can be very memory-intensive.
Unless you explicitly design your database so that it does not have a rowid, you can always try a quick solution
cur.execute("SELECT max(rowid) from Table")
n = cur.fetchone()[0]
This will tell you how many rows your database has.
I did it like
cursor.execute("select count(*) from my_table")
results = cursor.fetchone()
print(results[0])
this code worked for me:
import sqlite3
con = sqlite3.connect(your_db_file)
cursor = con.cursor()
result = cursor.execute("select count(*) from your_table").fetchall() #returns array of tupples
num_of_rows = result[0][0]
A simple alternative approach here is to use fetchall to pull a column into a python list, then count the length of the list. I don't know if this is pythonic or especially efficient but it seems to work:
rowlist = []
c.execute("SELECT {rowid} from {whichTable}".\
format (rowid = "rowid", whichTable = whichTable))
rowlist = c.fetchall ()
rowlistcount = len(rowlist)
print (rowlistcount)
The following script works:
def say():
global s #make s global decleration
vt = sqlite3.connect('kur_kel.db') #connecting db.file
bilgi = vt.cursor()
bilgi.execute(' select count (*) from kuke ') #execute sql command
say_01=bilgi.fetchone() #catch one query from executed sql
print (say_01[0]) #catch a tuple first item
s=say_01[0] # assign variable to sql query result
bilgi.close() #close query
vt.close() #close db file

Categories

Resources