Search for an element in SQL - python

I am writing a python script to search if an element pre-exists in my sql database.
def create_connection(db_file):
try:
conn = sqlite3.connect(db_file)
print(sqlite3.version)
except Error as e:
print(e)
main(conn) #function with inserts creates table and inserts values and calls find_values() function
def find_values(conn):
sql = ''' SELECT link_ID from links_table where link_ID="l_1234" '''
conn.execute(sql)
conn.commit()
Here I am comparing to something which I have already entered in my code like "l_1234". How will I compare it to something which is dynamic like a user entered variable?
Also how will I find if the element was found?

Have a look to this post :
How do I use SQL parameters with python?
or this one :
How to use variables in SQL statement in Python?
From one of the last post:
# Do this instead
t = ('RHAT',)
c.execute('SELECT * FROM stocks WHERE symbol=?', t)
print c.fetchone()

Related

python sqlite - deleting selected records

I'm trying to use sqlite3 in python to delete a selection of rows from a table. My attempt fails, but I can't work out why.
The sql query works ok, but I can't implement it within the python code.
I have a set of records that are moved from current_table to archive_table after a period of time.
I'd like to clean up the current_table by removing those rows that are in the archive_table (matched on id).
Intended SQL query:
DELETE FROM current_table WHERE id IN ( SELECT id FROM archive_table);
Attempted python code:
import sqlite3
def clean_up(current_table, archive_table):
db = sqlite3.connect(sqlite_db)
cursor = db.cursor()
sql_query_delete = '''DELETE FROM %s WHERE id IN ( SELECT id FROM %s);''' % (current_table, archive_table)
try:
cursor.execute(sql_query_delete)
db.commit()
db.close()
except:
print("error deleting")
Now working. The database file was locked by another process. Removing the pointless try/except led me to the detailed error message.

PyMySQL assigning a variable to table name, in Python

I am using PyMySQL in Python 2.7. I have to create a function - where, given a table name, the query will find unique values of all the column names.
Since there are more than one tables involved, I do not want to hard-code table name. Now, a simpler query is like:
cursor.execute(" SELECT DISTINCT(`Trend`) AS `Trend` FROM `Table_1` ORDER BY `Trend` DESC ")
I want to do something like:
tab = 'Table_1'
cursor.execute(" SELECT DISTINCT(`Trend`) AS `Trend` FROM tab ORDER BY `Trend` DESC ")
I am getting the following error:
ProgrammingError: (1146, u"Table 'Table_1.tab' doesn't exist")
Can someone please help. TIA
Make sure the database you're using is correct,and use %s to format you sql statement.
DB_SCHEMA='test_db'
table_name='table1'
connection = pymysql.connect(host=DB_SERVER_IP,
port=3306,
db=DB_SCHEMA,
charset='UTF8',
cursorclass=pymysql.cursors.DictCursor
)
try:
with connection.cursor() as cursor:
sql = "SELECT DISTINCT(`Trend`) AS `Trend` FROM `%s` ORDER BY `Trend` DESC"%(table_name)
cursor.execute(sql)
connection.commit()
except Exception as e:
print e
finally:
connection.close()
Hope this helps.

unable to insert data that are stored in variables in to an MYSQL database table using python

am trying to insert the data entered into the web form into database table,i am passing the data to the function to insert the data,but it was not successful below is my code
def addnew_to_database(tid,pid,usid,address,status,phno,email,ord_date,del_date):
connection = mysql.connector.connect(user='admin_operations', password='mypassword',host='127.0.0.1',database='tracking_system')
try:
print tid,pid,usid,address,status,phno,email,ord_date,del_date
cursor = connection.cursor()
cursor.execute("insert into track_table (tid,pid,usid,address,status,phno,email,ord_date,del_date) values(tid,pid,usid,address,status,phno,email,ord_date,del_date)")
cursor.execute("insert into user_table (tid,usid) values(tid,usid)")
finally:
connection.commit()
connection.close()
You should pass the variables as an argument to .execute instead of putting them in the actual query. E.g.:
cursor.execute("""insert into track_table
(tid,pid,usid,address,status,phno,email,ord_date,del_date)
values (%s,%s,%s,%s,%s,%s,%s,%s,%s)""",
(tid,pid,usid,address,status,phno,email,ord_date,del_date))
cursor.execute("""insert into user_table
(tid,usid)
values (%s,%s)""",(tid,usid))
You should tell us what API you are using and what the error code is.
You should define the values within the execution, right now within the sql statement as a string they are not referencing anything.
Typically when you use a variable name inside of a sql statement this way, you need to indicate that it is a variable you are binding data to. This might be replacing it with (1,2,3,4..) or (%s,%s,...) that corresponds to an ordered list or using variable names (:tid,:pid,...) that you then define the values of with a dictionary as the second argument of execute().
Like this:
track_table_data = [tid,pid,usid,address,status,phno,email,ord_date,del_date]
user_table_data = [tid,usid]
cursor.execute("insert into track_table (tid,pid,usid,address,status,phno,email,ord_date,del_date) values(1,2,3,4,5,6,7,8,9)", track_table_data)
cursor.execute("insert into user_table (tid,usid) values(1,2)",user_table_data)
or
cursor.execute("insert into track_table (tid,pid,usid,address,status,phno,email,ord_date,del_date) values(:tid,:pid,:usid,:address,:status,:phno,:email,:ord_date,:del_date))", {'tid':tid,'pid':pid,'usid':usid,'address':address,'status':status,'phno':status,'email':email,'ord_date':ord_date,'del_date':del_date})
cursor.execute("insert into user_table (tid,usid) values(:tid,:usid)",{'tid':tid,'usid':usid})

Python: How to check if an entry already exists in a sql database?

I'm new to python and even newer to sql, but I have been trying to make this work all morning and I cannot seem to figure it out. I have a table setup called POSTS(id). I'm trying to check if a number is already in the id column, but it doesn't matter what number postid is because data never returns none even if postid is set to a number not in the database.
import sqlite3 as lite
import sys
con = lite.connect('post.db')
postid = '52642'
cur = con.cursor()
cur.execute("select id from POSTS where id=?", (postid,))
data = cur.fetchall()
if data is None:
print ('not found')
else:
print ('found')
The statement
data = cur.fetchall()
will assign to data an empty list, not None, when nothing is found.
So just change your check to:
if not data:
instead of:
if data is None:

How to execute multi query in python?

I want to execute the sql_query given in below function and doing this way :
def get_globalid(self):
cursor = self.connect()
sql_query = "REPLACE INTO globalid (stub) VALUES ('a'); SELECT LAST_INSERT_ID() as id"
cursor = self.query(sql_query, cursor)
for row in cursor:
actionid = row[0]
return actionid
connect() function I am using to make a connection and it is defined separately .The query function i am using above is to execute any query passed to it . It is defined as :
def query(self,query,cursor):
cursor.execute(query)
self.close()
return cursor
It is not working properly . Is there anything I am missing ? Is there any mysqli function for python like that in php (multi_query) ?
mysql-python can't execute semicolon separated multiple query statement.
If you are looking for last_insert_id you can try with this:
conmy = MySQLdb.connect(host, user, passwd, db)
cursor = conmy.cursor()
sql_query = "REPLACE INTO globalid (stub) VALUES ('a')"
cursor.execute(sql)
last_insert_id = conmy.insert_id()
conmy.close()

Categories