Use placeholder to delete rows code in mysql with python mysqldb - python

conn = MySQLdb.connect(hostip, username, password, dbname)
cur = conn.cursor()
tablename = raw_input("Choose your table name: ")
if tablename:
cur.execute("SELECT * FROM %s" % tablename)
rows = cur.fetchall()
desc = cur.description
fields = [j[0] for j in desc]
for row in rows:
for kword in dust:
for fs in fields:
cur.execute("SELECT * FROM %s WHERE %s LIKE '%%s%'" % (tablename, fs, kword))
conn.close()
#
Like the simple code, i want to pass the params use %% PlaceHolder in mysqldb, but it doesn't worked, can somehelp me with that sentence? '%%s%' , first and last '%' is sql syntax that use 'like'
THANKS VERY MUCH !

There are two ways of format string using %s and {} show example as below:
print "key:%(key)s value:%(value)s" % {"key":"key1","value":"value1"}
print "{{keep me}} key:{key} value:{value}".format(**{"key":"key1","value":"value1"})
To solve your problem:
>>> "SELECT * FROM {tablename} WHERE {field} LIKE '%{keyword}%'".format(**{"tablename":"UserTable","field":"NameField","keyword":"Wuliang"})
"SELECT * FROM UserTable WHERE NameField LIKE '%Wuliang%'"

Related

Python MySQL Update Query

I am trying to update a SQL Table given a users input I have the following code. The user can choose to enter in/change the below fields which are defaulted to the values in the SQL table. However when I run the code I get the following error message
mysql.connector.errors.ProgrammingError: Not enough parameters for the SQL statement
I have counted it many times and it seems like the %s match the passed parameters. Am I missing something?
user = User_name_body.get('1.0',END)
passw = Password_text.get('1.0',END)
first = First_name.get('1.0',END)
last = Last_name.get('1.0',END)
phone = Phone_number.get('1.0',END)
email = Email_address.get('1.0',END)
mycursor = mydb.cursor()
sql = "UPDATE t_users SET Email_address=%s, First_name=%s, Last_name=%s, Phone_Number=%s, Password=%s WHERE User_Name=%s VALUES(%s,%s,%s,%s,%s,%s)"
val = (email, first, last, phone, passw,user)
mycursor.execute(sql, val)
mydb.commit()
mydb.close()
UPDATE does not take VALUES, you should change your sql query line to look like this:
sql = "UPDATE t_users SET Email_address=%s, First_name=%s, Last_name=%s, Phone_Number=%s, Password=%s WHERE User_Name=%s"
Python throws an error because you are asking for 12 parameters and only providing 6.
Prepare your sql data like this:
sql = """ UPDATE t_users SET Email_address=%s, First_name=%s, Last_name=%s, Phone_Number=%s, Password=%s WHERE User_Name = %s """
val = (email, first, last, phone, passw, user)
mycursor.execute(sql, val)
or you can do it like this
sql = "UPDATE btms_users SET btms_users.user='%s', btms_users.secret='%s' , btms_users.first_name='%s', " \
"btms_users.second_name='%s', btms_users.email='%s', btms_users.mobile='%s' " \
"WHERE btms_users.id='%s'" % (user_name, user_secret, user_firstname, user_lastname,
user_email, user_phone, user_id)
mycursor.execute(sql)
and here is a full working example:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="test",
database="test"
)
mycursor = mydb.cursor()
sql = "UPDATE items SET name = %s WHERE id = %s"
val = ("Test", 1)
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record(s) affected")

Error when updating a database table with pymssql and a python dictionary

I am trying to write data in a dictionary back into a SQL Server database table with pymssql.
But I am getting this error:
ValueError: more placeholders in sql than params available
Here is my code:
cursor = conn.cursor()
for key in dictW:
x = dictW[key]
sql = 'UPDATE tablename SET col = %s WHERE %s = #url '
cursor.executemany(sql, (key, x))
conn.commit()
conn.close()
What am I doing wrong here?
You are attempting to execute your queries one by one but are using executemany(). You should consider using a simple execute() instead:
cursor = conn.cursor()
for key in dictW:
x = dictW[key]
sql = 'UPDATE tablename SET col = %s WHERE %s = #url '
cursor.execute(sql, (key, x))
conn.commit()
conn.close()
If you want to use executemany(), you should make a list of tuples like this:
cursor = conn.cursor()
params = [(k, v) for k, v in dictW.items()]
sql = 'UPDATE tablename SET col = %s WHERE %s = #url '
cursor.executemany(sql, params)
conn.commit()
conn.close()

Python 3.4 transmiting table, columns and values as variables using MySQLdb

I am using Python 3.4
I have this piece of code:
import MySQLdb
table = "my_table"
columns = ("column1", "column2")
values = ("value1", "value2")
conn = MySQLdb.connect (host = "localhost",
user = "user",
passwd = "password",
db = "my_database")
cursor = conn.cursor()
# execute an insert
cursor.execute("INSERT INTO my_table column1, column2 VALUES (value1, value2)")
cursor.commit()
cursor.close()
conn.close()
Q: How can I pass the table name, columns and the values all as variables?
I would like to do something like this:
sql = "INSERT INTO %s %s VALUES %s" % (my_table, columns, values)
cursor.execute(sql)
You will have to do it as a 2 step process as the execute method will escape strings.
sql = "INSERT INTO {} ({}) VALUES ({})".format(table, ','.join(columns), ','.join('[%s]' * len(columns)))
# Generates: INSERT INTO my_table (column1,column2) VALUES (?,?)
cursor.execute(sql, values)

select multiple columns using SQLite3 in Python

I have a list that contains the name of columns I want to retrieve from a table in the database.
My question is how to make the cursor select columns specified in the list. Do I have to convert nameList to a string variable before include it in the select statement? Thanks
nameList = ['A','B','C','D',...]
with sqlite3.connect(db_fileName) as conn:
cursor = conn.cursor()
cursor.execute("""
select * from table
""")
As long as you can be sure your input is sanitized -- to avoid SQL injection attack -- you can do:
...
qry = "select {} from table;"
qry.format( ','.join(nameList) )
cursor.execute(qry)
If you're on a really old version of Python do instead:
...
qry = "select %s from table;"
qry % ','.join(nameList)
cursor.execute(qry)
nameList = ["'A(pct)'",'B','C','D',...]
with sqlite3.connect(db_fileName) as conn:
cursor = conn.cursor()
cursor.execute("""
select {} from table
""".format(", ".join(nameList)))

How can I format strings to query with mysqldb in Python?

How do I do this correctly:
I want to do a query like this:
query = """SELECT * FROM sometable
order by %s %s
limit %s, %s;"""
conn = app_globals.pool.connection()
cur = conn.cursor()
cur.execute(query, (sortname, sortorder, limit1, limit2) )
results = cur.fetchall()
All works fine but the order by %s %s is not putting the strings in correctly. It is putting the two substitutions in with quotes around them.
So it ends up like:
ORDER BY 'somecol' 'DESC'
Which is wrong should be:
ORDER BY somecol DESC
Any help greatly appreciated!
paramstyle
Parameter placeholders can only be used to insert column values. They can not be used for other parts of SQL, such as table names, statements, etc.
%s placeholders inside query string are reserved for parameters. %s in 'order by %s %s' are not parameters. You should make query string in 2 steps:
query = """SELECT * FROM sometable order by %s %s limit %%s, %%s;"""
query = query % ('somecol', 'DESC')
conn = app_globals.pool.connection()
cur = conn.cursor()
cur.execute(query, (limit1, limit2) )
results = cur.fetchall()
DO NOT FORGET to filter first substitution to prevent SQL-injection possibilities
Not all parts of an SQL query can be parametrized. The DESC keyword for example is not
a parameter. Try
query = """SELECT * FROM sometable
order by %s """ + sortorder + """
limit %s, %s"""
cur.execute(query, (sortname, limit1, limit2) )
You could try this alternatively...
query = """SELECT * FROM sometable
order by {0} {1}
limit {2}, {3};"""
sortname = 'somecol'
sortorder = 'DESC'
limit1 = 'limit1'
limit2 = 'limit2'
print(query.format(sortname, sortorder, limit1, limit2))

Categories

Resources