So I want to compare the input value with my database value. IF the input value is the same value as the database, I want to print(inputvalue). But if it's not the same, I want to print("Data Does Not Exist")
So I've tried this code :
cur = connection.cursor()
query = """ SELECT * FROM `foo` """
cur.execute(query)
result = cur.fetchall()
inputvalue = input("Input= ")
for x in result:
if inputvalue not in x:
print("Data Does Not Exist")
else:
print(inputvalue)
and this is the output:
inputvalue= 1728192
Data Does Not Exist
Data Does Not Exist
Data Does Not Exist
Data Does Not Exist
1728192
Data Does Not Exist
Data Does Not Exist
Data Does Not Exist
I expect the output is
Inputvalue= 1728192
Data Does Not Exist
If the Data Does Not Exist,
And this output:
Inputvalue= 1728192
1728192
If the Data Exist
Any answer would be appreciated!
Instead of loading all the rows from foo into python, I would suggest to query if that specific value is in your database. Databases are optimised for such a request. And if there is a lot of data in your database, your approach would need a lot of time to load everything into memory (which can easily result in a memoryError).
So I guess you store your values in a column called 'bar':
inputvalue = input("Input= ")
cur = connection.cursor()
query = """ SELECT * FROM `foo` WHERE bar = inputvalue """
cur.execute(query)
row_count = cur.rowcount
if row_count > 0:
print(inputvalue)
else:
print("Data Does Not Exist")
And for you to understand why your approach is not working as expected: With for x in result: you loop through every row in your table, and for each row, you check if inputvalue is in there.
you can make boolean object and after executing compare your answer :
cur = connection.cursor()
query = """ SELECT * FROM `foo` """
cur.execute(query)
result = cur.fetchall()
inputvalue = input("Input= ")
temp = False
for x in result:
if inputvalue in x:
temp = True
if temp:
print(inputvalue)
else:
print("Data Does Not Exist")
Related
I have managed to update database with several databases located in specific directory like this:
path2 = r'C://Users//samor//Session//KOPIA BAZ'
paths = []
try:
for file in os.listdir(path2):
if file.endswith('.db'):
paths.append(file)
except:
print("Ścieżka nie istnieje")
df = pd.DataFrame(paths)
print(str(df.iloc[0, 0]))
db_conn = sqlite3.connect(os.path.join(path2, str(df.iloc[0, 0])))
c = db_conn.cursor()
c.executescript("""ATTACH DATABASE 'baza kalkulacji.db' AS other;
INSERT INTO other.baza_kalkulacji (Numer_Kalkulacji,Sciezka_Kalkulacji,Opis_Kalkulacji)
SELECT Numer_Kalkulacji,Sciezka_Kalkulacji,Opis_Kalkulacji
FROM baza_kalkulacji;""")
db_conn.commit()
db_conn.close()
db_conn = sqlite3.connect('baza kalkulacji.db')
c = db_conn.cursor()
c.execute("""
delete from baza_kalkulacji
where rowid not in (select min(rowid)
from baza_kalkulacji
group by Numer_Kalkulacji,Sciezka_Kalkulacji,Opis_Kalkulacji) """)
db_conn.commit()
db_conn.close()
But the problem is...the number of databases will grow in time so i should add copy of the above code hundreds of time while changing value of row in :
db_conn = sqlite3.connect(os.path.join(path2, str(df.iloc[0, 0])))
So the question is:
IS there any solution to add this for loop or something that will connect to next and next database that is in that directory and will keep on inserting these tables like i did in code? Like automatically changing that value for a row in df.iloc ????
I figure it out like this:
path2 = r'C://Users//samor//Session//KOPIA BAZ'
paths = []
try:
for file in os.listdir(path2):
if file.endswith('.db'):
paths.append(file)
except:
print("Ścieżka nie istnieje")
df = pd.DataFrame(paths)
# print(df)
# print(str(df.iloc[0, 0]))
index = df.index
number_of_rows = len(index)
print(number_of_rows)
for bazy in range(number_of_rows):
db_conn = sqlite3.connect(os.path.join(path2, str(df.iloc[bazy, 0])))
c = db_conn.cursor()
c.executescript("""ATTACH DATABASE 'baza kalkulacji.db' AS other;
INSERT INTO other.baza_kalkulacji (Numer_Kalkulacji,Sciezka_Kalkulacji,Opis_Kalkulacji)
SELECT Numer_Kalkulacji,Sciezka_Kalkulacji,Opis_Kalkulacji
FROM baza_kalkulacji;""")
c.execute("DETACH DATABASE 'other'")
db_conn.commit()
db_conn.close()
db_conn = sqlite3.connect('baza kalkulacji.db')
c = db_conn.cursor()
c.execute("""
delete from baza_kalkulacji
where rowid not in (select max(rowid)
from baza_kalkulacji
group by Numer_Kalkulacji) """)
db_conn.commit()
db_conn.close()
hi i am looking to insert these 3 values into my SQL database table that has columns: email, cardnumber, dateandtime
here is my code:
email = input("Email: ")
cardnumber = int(input("Enter card number:"))
now = datetime.now()
now = now.strftime('%Y-%m-%d %H:%M:%S')
newrowforsql()
my code for the query is:
def newrowforsql():
query = """\
insert into table1 (email,cardnumber,dateandtime)
values(email,cardnumber,now)"""
insertnewrow = execute_query_commit(conn, query)
I cant seem to insert the values
my code for executing the query and committing it is:
def execute_query_commit(connection, query):
cursor = connection.cursor()
try:
cursor.execute(query)
connection.commit()
print("Query executed and committed")
except pyodbc.Error as e:
print(f"The error '{e}' occurred")
As "azro" mentioned correctly you didn't put in the variable content to the query, you just put in the name of the variable which contains the information you want. What you need to change is the following:
def newrowforsql():
query = """\
insert into table1 (email,cardnumber,dateandtime)
values(email,cardnumber,now)"""
insertnewrow = execute_query_commit(conn, query)
to
def newrowforsql():
query = """\
insert into table1 (email,cardnumber,dateandtime)
values({theEmail},{theCardnumber},{now})""".format(theEmail=email, theCardnumber=cardnumber, now=now)
insertnewrow = execute_query_commit(conn, query)
This is one of the most used options to manipulate strings in python. But if you are using python3.7+ (maybe from Python3.6 and up, but I'm not sure) there is a much better and faster option to manipulate strings, it's name is "f-strings".
Here is the same solution but with f-strings instead of the method str.format
def newrowforsql():
query = f"""\
insert into table1 (email,cardnumber,dateandtime)
values({email},{cardnumber},{now})"""
insertnewrow = execute_query_commit(conn, query)
Good luck!
I'm trying to execute the same query but with different data but I always get data the first time. The others times, dispite of there are data for the querys in the data base, mysql returns empty data.
This is the code:
def get_team_colour_map(self, players, id_competition):
tcm = FIBAColourMap()
for p in players:
args = [p["id"], id_competition]
conn = pymysql.Connect(host = DDBB.DDBB_FIBA_HOST,
user = DDBB.DDBB_FIBA_USER,
password = DDBB.DDBB_FIBA_PSWD,
db = DDBB.DDBB_FIBA_NAME,
charset = DDBB.DDBB_FIBA_CHARSET,
cursorclass=pymysql.cursors.DictCursor)
with conn.cursor() as cursor:
print("id player: {}".format(p["id"]))
print("args: {}".format(args))
cursor.execute("select sc.* from tbl030_shots_chart sc, tbl006_player_team pt, tbl007_game g, tbl004_jornada j, tbl012_competition c where pt.id = %s and pt.id_player_feb = sc.id_fiba and sc.id_game = g.id and g.id_jornada = j.id and j.id_competition = c.id and c.id = %s", args)
data = cursor.fetchall()
print("data: {}".format(data))
print("Total rows: {}".format(cursor.rowcount))
if cursor.rowcount > 0:
for s in data:
x = float(FIBASCReport.adjust_x(s["x"]))
y = float(FIBASCReport.adjust_y(s["y"]))
color = tcm.image.getpixel((x,y))
color = ("#%02x%02x%02x" % color).upper()
if tcm.exists_color(color):
if int(s["m"]) == 0:
tcm.set_scored_shots(color, 1)
else:
tcm.set_failed_shots(color, 1)
else:
if int(s["m"]) == 0:
tcm.set_scored_shots("OTROS", 1)
else:
tcm.set_failed_shots("OTROS", 1)
else:
#tcm = None
print("Jugadora con id: {} NO ha realizado ningún tiro en competición: {}".format(p["id"], id_competition))
return tcm
In this code, cursor.fetchall() returns data the first query but the next querys returns empty results.
How can I run several querys? I'm using mySQL 8.0 and Python 3.6
Its because you are using the same cursor each time. create a new instance of the cursor each time you loop through to excecute the query. After the first query is run the cursor is already positioned after all the data. Hence no rows returned after that
You can also try this:
Look at the documentation for MySQLCursor.execute().
It claims that you can pass in a multi parameter that allows you to run multiple queries in one string.
If multi is set to True, execute() is able to execute multiple statements specified in the operation string.
multi is an optional second parameter to the execute() call:
operation = 'SELECT 1; INSERT INTO t1 VALUES (); SELECT 2'
for result in cursor.execute(operation, multi=True):
I am using a code that is using mysql. I am very new in mysql so I would be thankful if you could help. My input is a huge dumpfile of wikipediapages in xml bz2 format. The input format is some text files extracted from that xml file with this format:
<doc id="12" url="https://en.wikipedia.org/wiki?curid=12" title="Anarchism"> text... </doc>
the only parts that connects the program to sql is as follows:
def read_in_STOP_CATS(f_n = "/media/sscepano/Data/Wiki2015/STOPCAT/STOP_CATS.txt"):
s = []
f = open(f_n, "r")
for line in f:
s.append(line.rstrip().lower())
return s
def connect_2_db():
try:
cnx = mysql.connector.connect(user='test', password='test',
host='127.0.0.1',
database='wiki_category_links')
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with your user name or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist")
else:
print(err)
return cnx
def articles_selected(aid):
global cnx
global STOP_CATS
cursor = cnx.cursor(buffered=True)
cursor.execute("SELECT * FROM categorylinks where cl_from = " + str(aid))
row = cursor.fetchone()
while row is not None:
#print(row)
cat = row[1].lower()
#print cat
for el in STOP_CATS:
if el in cat:
return False
row = cursor.fetchone()
return True
cnx = connect_2_db()
STOP_CATS = read_in_STOP_CATS()
TITLE_WEIGHT = 4
my problem is that right now I do not know how should I connect to mysql to be able to run the code and the main prob;lem is that I do not know what is categorylinks in the code? That should be the name of my sql table? Does it mean that I need to make an sql table with this name and import all my text file in this one table?
what does 'where' means in this line also????
As RiggsFolly said, you need to get something like WHERE cl_from = 'some string'
You could do it this way:
cursor.execute("SELECT * FROM categorylinks where cl_from ='" + str(aid)+"'")
But it is better to use prepared statements like this one:
select_stmt = "SELECT * FROM categorylinks where cl_from = %(aid)s"
cursor.execute(select_stmt, { 'aid':str(aid) })
So in your code you have:
A database named wiki_category_links
In that database you have a table called categorylinks
And the select you have means that you are going to get, from table categorylinks, all rows that have the column cl_from equal to the value of aid variable.
I am writing a python script to perform some specific task if an element ID pre-exists. I have created a database where I am saving the data elements.
I want to find out if the element link_ID exists in the database or not. How will I do that?
I have written a small script which is not perfect. The output I am getting is No such element exists.
link_ID = link_1234
sql = ''' SELECT link_ID from link_table where link_ID=? '''
var = (link_ID)
conn.execute(sql, [var])
conn.commit()
if conn.execute(sql, [var]) == True:
print("Search Successful")
flag = 1
else:
print("No such element exists")
flag = 0
You have a number of problems here. First, you should create a cursor object from your connection and use that to execute your query:
c = conn.cursor()
c.execute(sql,var)
Secondly, execute wants a tuple of values to interpolate, not a list, so do this:
var = (link_ID,)
c.execute(sql,var)
Or:
c.execute(sql,(link_ID,))
Lastly, c.execute returns the cursor object rather than the success of the query. You should fetch the result of the query using fetchone(), if your query didn't return a row then the return value of fetchone() will be None:
result = c.fetchone()
if result is not None:
print('Success:',result)
else:
print('No row found for', link_ID)