I'm executing this code in python
from sqlite3 import dbapi2 as sqlite
con = sqlite.connect("db.sqlite")
cur = con.cursor()
surname = "'%atton%'"
cur.execute("select id from singers where surname like :surname", locals())
cur.close()
con.close()
After this code cur.rowcount == -1 but Patton is in the database.
Is my SQL statement bad?
thank you
The DB-API parameterization you use (which you should use, don't change that) means the surname will automatically be quoted or escaped appropriately. You should remove the inner set of quotes from your surname string.
surname = "%atton%"
cur.execute("select id from singers where surname like :surname",
dict(surname=surname))
Related
I'm trying to get the value of name=a and get the data there
But I'm getting
sqlite3.OperationalError: no such column: a
#app.route('/editform/<_name>')
def editform(_name):
db = sql.connect("database.db")
cursor = db.cursor()
cursor.execute('SELECT * FROM students WHERE name= %s' %_name)
That's because you use string formatting to substitute %s with the value of _name, ending up with
SELECT * FROM students WHERE name= a
Note that a here is interpreted to be a column name because it is not between quotes (i.e. "a").
Don't use string formatting for SQL statements as you will be vulnerable to SQL injection attacks. Use the proper placeholder syntax:
cursor.execute('SELECT * FROM students WHERE name=?', (_name,))
My Python code uses pyodbc to connect to a database and then asks the user for input which I would like to format the 'where' clause in an SQL statement but the where clause requires single quotation marks on my user input to function.
Every time I have tried to format the input to include single quotation mark it doesn't seem work and returns back no rows.
Here is what I am trying to achieve
"select FirstName, LastName from person.person where FirstName = 'Kim'"
where 'Kim' should be the user input.
here in my code section.
user_first_name = print(input("Enter the first name you are looking
for: "))
cursor.execute("select FirstName, LastName from person.person where
FirstName = ?", (user_first_name))
how do I format the input (user_first_name) so that the parameter has the single quotes in the query field.
import pyodbc
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=DESKTOP-3NLISNE\SQLNEW;DATABASE=TestDB;UID=python;PWD=password')
cursor = cnxn.cursor()
user_first_name = print(input("Enter the first name you are looking for:"))
query = "select FirstName, LastName from person.person where FirstName = ?"
result = cursor.execute(query, (user_first_name,))
rows = result.fetchall()
print (rows)
I'm trying to insert a variable inside one SQL query using "+uid+" but the variable does not seem to be taken into account:
import datetime
import sqlite3 as lite
import sys
con = lite.connect('user.db')
uid = raw_input("UID?: ")
time = datetime.datetime.now()
with con:
cur = con.cursor()
cur.execute("SELECT Name FROM Users WHERE Id = "+uid+";")
rows = cur.fetchall()
for row in rows:
print row
print time
Do not use string manipulation on SQL. It can result in sql-injections.
Change
cur.execute("SELECT Name FROM Users WHERE Id = "+uid+";")
to (using prepared statements)
cur.execute("SELECT Name FROM Users WHERE Id=?;", (uid,))
cur.execute("SELECT Name FROM Users where %s=?" % (Id), (uid,))
also check out this answer
Python sqlite3 string variable in execute
I have created a table, and have inserted data into the table. I wanted to know how I could update/edit the data. For example, if I have multiple columns in the table, of which one is named 'age' and the data for the column is = '17', and I now wanted to replace '17' with '18', would I do the following?
import sqlite3 as lite
import sys
con = lite.connect('Records.db')
with con:
cur = con.cursor()
cur.execute("INSERT INTO ExampleTable(Age) VALUES(18) WHERE (Age = 17)")
In sqlite3 with Python3.x works to me something like this:
newPrice = '$19.99'
book_id = 4
cursor.execute('''UPDATE books SET price = ? WHERE id = ?''', (newPrice, book_id))
To update values in a SQL database using the SQLite library in Python, use a statement like this one.
cur.execute("UPDATE ExampleTable SET Age = 18 WHERE Age = 17")
For a great introduction to using SQLite in Python, see this tutorial.
I'm not into Python, but i think i can help, so
cur.execute("UPDATE ExampleTable SET age = 18 WHERE age = 17")
If i'm wrong, sorry then
with con:
cur = con.cursor()
cur.execute("UPDATE Table_Name SET Age='18' WHERE Age='17'")
you must use update operation Instead of insert operation to change records.
the program would be as follows
cur=con.cursor()
com="update ExampleTable set age=1 where age=17"
try:
cur.execute(com)
con.commit()
except:
print('error')
con.rollback()
con.close()
I am writing a program in which two variables are selected from QCombobBoxes which are populated with results from a MySQL query. I then take these variable and insert them into a MySQLdb statement that inserts the variables into a different MySQL table. The first variable works fine, however on the second I get this error,
TypeError: 'NoneType' object has no attribute '__getitem__'
The code is identical for both variables, with the exception of different names
name = str(self.item_name.currentText())
cur.execute("SELECT item_id FROM Items WHERE name = '%s';"), name
db.commit()
results = cur.fetchone()
item_name = results[0]
personnel_name = str(self.purchaser_name.currentText())
cur.execute("SELECT personnel_id FROM Personnel WHERE name = '%s';"), personnel_name
db.commit()
results = cur.fetchone()
purchaser_id = results[0]
After playing with it, it looks like cur.execute("SELECT item_id FROM Items WHERE name = '%s';"), name is inserting an extra pair of quotation marks around the value that replaces %s Does anyone know why it's doing this and how to stop it? I coded both variables exactly the same, and it seems that name is getting an extra pair of quotes from MySQL
This is code that populates QComboBox:
#Get list of items currently in the database
cur = db.cursor()
cur.execute("SELECT name FROM Items")
db.commit()
results = cur.fetchall()
for name in results:
self.item_name.addItem(name[0])
#Get list of purchaser names
cur.execute("SELECT name FROM Personnel")
db.commit()
results = cur.fetchall()
for name in results:
self.purchaser_name.addItem(name[0])
If I manually insert a variable, it works fine. ex: cur.execute("SELECT item_id FROM Items WHERE name = 'Wire';") Only when I use string formatting with %s does the error occurr.
c.execute("SELECT * FROM sometable WHERE some_condition=?","My Condition")
you should always use the ? placeholders for this kind of thing
[edit]
try 1. cur.execute("SELECT item_id FROM Items WHERE name = '%s';"%(name,))
or 2. cur.execute("SELECT item_id FROM Items WHERE name = %s;", (name,))
from my brief reading, I think that mysql driver will automatically quote %s arguments
my conclusion is that cur.execute("SELECT item_id FROM Items WHERE name = %s;", (name,)) is the most correct way to do this(to avoid injection etc).