How to Pass a Variable to SEARCH database in Python - Sqlite - python

I am trying to pass a variable to search for the row from SQLite DB and print out the results. Here is the code below thats causing the problem:
find_domain = 'domain.com'
def searchdomain(locate):
row = sql.execute("SELECT * FROM blocked_domains WHERE name = ?;",(locate,))
print(row)
searchdomain(find_domain)
No error comes up, it just come back blank.

Ensure that you have created a cursor object for data retrieval:
import sqlite3
conn = sqlite3.connect('tablename.db')
data = list(conn.cursor().execute("SELECT * FROM blocked_domains WHERE name = ?;", (locate,)))

Related

Python + MySQL: Search function returning all entries

I'm putting together an inventory program using Python and MySQL. I want to implement a search function that returns entries based on user input (programmed in a separate GUI file). In the code below, I expected that the search function would return entries with the brand "UGreen". Instead, it returns all of the entries in the table.
I'm not sure what I'm doing wrong here. I have used a similar structure in another program with a sqlite database instead and the search worked fine.
Any and all help/suggestions would be greatly appreciated :)
import mysql.connector
equipdb = mysql.connector.connect(
host = "localhost",
user = "root",
password = "REDACTED",
database = "tel_inventory"
)
def view():
cur = equipdb.cursor()
cur.execute("SELECT * FROM equipment")
result = cur.fetchall()
return result
def search(name="", brand="", model="", consumables="", storage="", room="", photo=""):
cur = equipdb.cursor()
cur.execute("SELECT * FROM equipment WHERE name=%s OR brand=%s OR model=%s OR consumables=%s OR storage=%s OR room=%s OR photo=%s", (name, brand, model, consumables, storage, room, photo))
result = cur.fetchall()
return result
#print(view())
print(search(brand="UGreen"))
Try using keyword argument directly
def search(**kwargs):
cur = equipdb.cursor()
key = str(list(kwargs.keys())[0])
value = str(kwargs[key])
cur.execute('SELECT * FROM equipment WHERE {} = "{}"'.format(key,value))
result = cur.fetchall()
return result

The Code is not working in jupyter and giving the error as pictured below [duplicate]

I am trying to query on a local MySQL database using Python's (3.4) MySQL module with the following code:
class databases():
def externaldatabase(self):
try:
c = mysql.connector.connect(host="127.0.0.1", user="user",
password="password", database="database")
if c.is_connected():
c.autocommit = True
return(c)
except:
return(None)
d = databases().externaldatabase()
c = d.cursor()
r = c.execute('''select * from tbl_wiki''')
print(r)
> Returns: None
As far as I can tell, the connection is successful, the database is composed of several rows but the query always returns the none type.
What instances does the MySQL execute function return None?
Query executions have no return values.
The pattern you need to follow is:
cursor creation;
cursor, execute query;
cursor, *fetch rows*;
Or in python:
c = d.cursor()
c.execute(query) # selected rows stored in cursor memory
rows = c.fetchall() # get all selected rows, as Barmar mentioned
for r in rows:
print(r)
Also some db modules allow you to iterate over the cursor using the for...in pattern, but triple-check that regarding mysql.
For my case, I return the cursor as I need the value to return a string specifically, for instance, I return the password (string) for inspect whether user used the same password twice. Here's how I did it (In my case):
def getUserPassword(metadata):
cursorObject.execute("SELECT password FROM users WHERE email=%s AND password=%s LIMIT 1", (metadata['email'], metadata['password']))
return cursorObject.fetchall()[0]['password']
Which I can easily call from another class by calling the method:
assert getUserPassword({"email" : "email", "password" : "oldpass"}) is not None
And which the getUserPassword itself is returning a string

Python SQLite3 Retrieve Variables From SELECT Query

I'm busy writting a python script that is querying two db tables to build a single row of data per row it finds. Here is my script at the moment
#========================================================================
# DB CONNECT FUNCTION
#========================================================================
def f_connect(status):
global gv_conn
global gv_curs
if status == 1:
gv_conn = sqlite3.connect("./data.db")
gv_curs = gv_conn.cursor()
else
gv_conn.close()
#========================================================================
# PREPARE SQL STATEMENTS
#========================================================================
def f_statements():
global users_stmt
users_stmt = ("select * from users")
global users_curs
users_curs = gv_conn.cursor()
global uinfo_stmt
uinfo_stmt = ("select * from uinfo" +
"where ui_u_id = ?")
global uinfo_curs
uinfo_curs = gv_conn.cursor()
#========================================================================
#
# MAIN SCRIPT START
#
#========================================================================
f_connect(1)
f_statements()
la_users = []
for u_row in users_curs.execute(users_stmt):
# THIS LINE GETS USERS FROM THE ABOVE STATEMENT
# AND ADDS THEM TO THE DICTIONARY
la_users.append({"u_id": u_row[0], "u_name": u_row[1]})
# THIS LINE EXECUTES ANOTHER QUERY TO RETRIEVE
# A SINGLE ROW OF DATA FROM ANOTHER TABLE
la_uinfo = uinfo_curs.execute(uinfo_stmt, "1")
f_connect(0)
My problem is that when I execute the first sql statement I can get get the data by looping using a for loop which is storing the data so i can access it using u_row[int].
When I execute the second query it is storing it inside la_uinfo although when I try to get the data from la_uinfo[int] it doesn't work? How can I retrieve the data from my second query without using another for loop? (I shouldn't have to considering it only returns one row)
Cursors are not indexable, so cursor[0] will not work. To retrieve the first row of a cursor, you should use cursor.fetchone().

Can't use cx_Oracle LOB in Spatialite WKB insert statement

I have some Python code the selects data from Oracle spatial and inserts into Spatialite. My problem is that the cursor contains the geometry in binary and I can’t figure out how to read the binary into the Spatialite insert statement. Just to added this all works if I use WKT but some of the geometries are too long hence the reason for the binary format.
Can anyone help please?
# Import system modules
import cx_Oracle
from pyspatialite import dbapi2 as sl_db
def db_connect():
# Build connect from TNS names
o_db = cx_Oracle.connect("xxxxx", "xxxxx", "xxxxx_gl_dev")
cursor = o_db.cursor()
return cursor
def db_lookup(cursor):
# Select records
sql = "SELECT sdo_util.to_wkbgeometry(a.shape), a.objectid FROM span a WHERE a.objectid = 1382372"
cursor.execute(sql)
row = cursor.fetchall()
return row
def db_insert(row):
# Insert Rows in new spatailite table
database_name = 'C:\\Temp\\MYDATABASE.sqlite'
db_connection = sl_db.connect(database_name)
db_cursor = db_connection.cursor()
sql = 'INSERT INTO "SPAN_OFL" ("geometry", "OBJECTID") Values GeomFromWKB(?,27700),?);'
db_cursor.executemany(sql, row)
db_connection.commit()
db_connection.close()
# main code
cursor = db_connect()
row = db_lookup(cursor)
db_insert(row)

Writing code to codes.db incorrectly

I am trying to make a random code generator in python that writes to a database. I have the codes generating and writing to the database, but instead of adding full codes to the database it loops through letters. Here is my code for the code generator:
import string
import random
import sqlite3
def id_generator():
db = sqlite3.connect('codes.db')
c = db.cursor()
number_of_codes = 10
stringLength = 9
id_code = input("what letter should this begin with: \n")
id_code = id_code.upper()
dict_ofcodes = []
for x in range(0, number_of_codes):
codez = (''.join(random.choice(string.ascii_uppercase) for i in range(stringLength)))
final_codez = (id_code + codez)
dict_ofcodes.insert(x, final_codez)
print (dict_ofcodes)
dict_ofcodes_tuple = tuple(dict_ofcodes)
print(dict_ofcodes_tuple)
for x in range(0, number_of_codes):
c.executemany(''' INSERT INTO codes(codes) VALUES(?)''', dict_ofcodes_tuple[x])
db.commit()
db.close()
id_generator()
Here is what it prints
['AALRRIULNC', 'AZTKZBKTLK', 'ATWMWYWICO', 'AWQJIJYEJH', 'AQFIONPUNJ', 'AMJRXUIJXM', 'AUDRLSBLSG', 'ABXYXDUMPD', 'AUAXRQURBH', 'ADQEVIRDFU']
('AALRRIULNC', 'AZTKZBKTLK', 'ATWMWYWICO', 'AWQJIJYEJH', 'AQFIONPUNJ', 'AMJRXUIJXM', 'AUDRLSBLSG', 'ABXYXDUMPD', 'AUAXRQURBH', 'ADQEVIRDFU')
It writes to the database single letters of the codes:
A
F
Y
and so on
The code I used to create the schema is contained in the a python file
import sqlite3
def writeDB():
db = sqlite3.connect('codes.db')
c = db.cursor()
# Create table
c.execute('''CREATE TABLE codes (codes TEXT)''')
# Save (commit) the changes
db.commit()
#can also close the connection if done with it.
# be sure any changes have been committed or they will be lost.
db.close()
writeDB()
I created the file with the mac terminal.
How could I write the full codes to the database?
The problem is with this line:
c.executemany(''' INSERT INTO codes(codes) VALUES(?)''', dict_ofcodes_tuple[x])
executemany is used to iterate over a list of parameters and call the sql statement for each parameter. So your dict_ofcodes_tupel[x] is treated as a character array and the INSERT is called for each character.
If you want to insert the entire string as one, use execute() instead.
c.execute(''' INSERT INTO codes(codes) VALUES(?)''', (dict_ofcodes_tuple[x],))
or
c.execute(''' INSERT INTO codes(codes) VALUES(?)''', [dict_ofcodes_tuple[x]])

Categories

Resources