How do i get the sqlite3 column - python-2.7

My code:
import sqlite3
conn = sqlite3.connect("keywords.db")
def search_location(name2):
name3 = ' '.join(name2)
c = conn.cursor()
c.execute('SELECT location FROM INPUT WHERE id = ?', (name3,))
for (location,) in c:
print name3.capitalize(),':' '\n',location
break
else:
pass # not found
Sqlite table:
sqlite>
CREATE TABLE input(
ID INT PRIMARY KEY AUTOINCRREMENT, NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY ....
);
I keep getting the error: No column LOCATION found. Items in name3 are to match the items in column NAME. If I change the code to read :
'SELECT NAME FROM INPUT WHERE id = ?', (name3,)
The error is the same. Please refer to the question I had asked earlier on How to improve sqlite database request and speed

Related

replacing variable in SQL statement using django

I have a problem when using raw sql query which has a variable table name like
cursor.execute("SELECT description FROM %s WHERE id = 1", [table_name])
%s replaces the string in double quote which isn't executing properly.When I execute the above statement I get
"NameError: name 'nike_tshirts' is not defined"
Your should just put the table name between quotes 'table_name' / "table_name" or define the variable before: table_name = 'nike_tshirts'.
So:
cursor.execute("SELECT description FROM %s WHERE id = 1", 'nike_tshirts')
or
table_name = 'nike_tshirts'
cursor.execute("SELECT description FROM %s WHERE id = 1", table_name)
should work just fine.
Python raises a NameError because it thinks you are referring to a variable, when you are trying to refer to a string.

How to improve sqlite database request and speed

I found put that I open the database at every request.Is there a way to simplify and improve this code to increase the sqlite speed?
name3 = ' '.join(name2)
import sqlite3
id = 0
location = ""
conn = sqlite3.connect("keywords.db")
c = conn.cursor()
c.execute('select * from kmedicals')
records = c.fetchall()
for record in records:
id = record[0]
location = record[15]
if id == name3:
print name3.capitalize(),':' '\n',location
break
sys.exit()
Do not use import in the middle of your program.
Open the database once at the start of your program.
Select only the records you actually need.
Select only the columns you actually need.
Do not use fetchall; read only the records you actually need.
Do not fetch into a temporary variable if you can use the cursor directly.
import sqlite3
# at startup
conn = sqlite3.connect("keywords.db")
def search_location(name2):
name3 = ' '.join(name2)
c = conn.cursor()
c.execute('SELECT location FROM kmedicals WHERE id = ?', (name3,))
for (location,) in c:
print name3.capitalize(),':' '\n',location
break
else:
pass # not found

How to parse SQL Queries and sub queries using sqlparser into python

Want to parse sql join query, select sub query into python. I am using sqlparse library. But i could not parse sub query. How i can parse whole query.
e.g:
query = "select id,fname,lname,address from res_users as r left join res_partner as p on p.id=r.partner_id where name = (select name from res_partner where id = 1)"
query_tokens = sqlparse.parse(query)[0].tokens
I could not parse for this select name from res_partner where id = 1 sub query.
Not so elegant, but works:
import sqlparse
from sqlparse.sql import Where, Comparison, Parenthesis
query = """
select
id,fname,lname,address
from
res_users as r
left join
res_partner as p
on
p.id=r.partner_id
where
name = (select name from res_partner where id = 1)"""
query_tokens = sqlparse.parse(query)[0]
where = next(token for token in query_tokens.tokens if isinstance(token, Where))
condition = next(token for token in where.tokens if isinstance(token, Comparison))
subquery = next(token for token in condition.tokens if isinstance(token, Parenthesis))
print subquery
prints:
(select name from res_partner where id = 1)
This library can parse and generate SQL https://code.google.com/p/python-sql/

How to check a table exists in sqlite3 or not

I am new to SQL. I want to check that a table exist in data base or not. If it does not exist than create it. Also I want to check that a record exist in table or not. If exists than update it with new data, If does not exist than insert a new record in table. Here is the code. I don't know how to check for a existing table,record.
import sqlite3 as lite
con = lite.connect('test.db')
cur = con.cursor()
con.execute('''CREATE TABLE EMPLOYEE
(ITEMA TEXT PRIMARY KEY NOT NULL,
ITEMB CHAR(50) NOT NULL,
ITEMC CHAR(50),
ITEM0 TEXT
ITEM1 TEXT
ITEM2 TEXT
ITEM3 TEXT
ITEM4 TEXT);''')
con.execute("INSERT INTO EMPLOYEE (ID,NAME,ADDRESS,MOBILE_NUMBER,TRANSPORT_FOR_LUNCH,ONLY_DROP,KIDS,ADULTS) \
VALUES (%s,%s',%s,%s,%s,%s,%s,%s)" %(ia,ib,ic,i0,i1,i2,i3,i4));
To test for table existence in sqlite, you can do something like:
cursor = con.cursor()
statement = "SELECT name FROM sqlite_master WHERE type='table';"
if (table_name,) in cursor.execute(statement).fetchall():
print "Table %s exists." % table_name
To update or create depending upon pre-existence of a record, sqlite allows the use of replace, which is an alias for insert or replace:
replace into table_name (columns) values (values)
CREATE TABLE EMPLOYEE IF NOT EXISTS ..
creates only if it does not exist

SQLite: how to SELECT a range of records?

I want to create a DB table and a set of commands for it. So currently I have
this->command_create_files_table = "CREATE TABLE IF NOT EXISTS files (encoded_url varchar(300) UNIQUE NOT NULL primary key, file_name varchar(150) NOT NULL, user_name varchar(65) NOT NULL, is_public BOOLEAN NOT NULL, modified DATETIME NOT NULL default CURRENT_TIMESTAMP )";
this->command_create_file = "INSERT INTO files (encoded_url, file_name, user_name, is_public ) VALUES (:encoded_url, :file_name, :user_name, :is_public)";
this->command_update_file = " UPDATE files SET encoded_url=:new_encoded_url, file_name=:new_file_name, is_public=:is_public, modified=CURRENT_TIMESTAMP WHERE encoded_url=:encoded_url";
this->command_delete_file = "DELETE FROM files WHERE encoded_url=:encoded_url";
this->command_find_file = "SELECT file_name, user_name, is_public, modified FROM files WHERE encoded_url=:encoded_url";
this->command_find_all_user_files = "SELECT encoded_url, file_name, user_name, is_public, modified FROM files WHERE user_name=:user_name";
(using sqlite3pp syntax here)
I wonder how to SELECT some predefined :N (25 for example - no more) files or less from some start DATETIME point (CURRENT_TIMESTAMP for example)?
SELECT
fields_you_want_to_select
FROM
filesTbl
WHERE
DATETIME > start_of_range AND
DATETIME < end_of_range
LIMIT limit_num
SELECT
fields_you_want_to_select
FROM
filesTbl
WHERE
DATETIME > start_of_range AND
DATETIME < end_of_range
LIMIT
25