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

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)

Related

Mysql table name getting unwanted quotes resulting table does not exist error

import mysql.connector
def add_features_to_db(stockname, timeframe, date, feature):
try:
conn = mysql.connector.connect(
user='root', password='', host='localhost', database='fx003')
cursor = conn.cursor()
dbtable = stockname + timeframe
mySql_insert_query = """INSERT INTO `%s` (date, trend) VALUES ( `%s`, `%s` )"""
record = (dbtable, date, feature)
cursor.execute(mySql_insert_query, record)
conn.commit()
print("Record inserted successfully")
except mysql.connector.Error as error:
print("Failed to insert into MySQL table {}".format(error))
finally:
if conn.is_connected():
cursor.close()
conn.close()
print("MySQL connection is closed")
add_features_to_db("aud-cad", "_30mins", "2021-09-24 21:00:00", "Short")
I have the code above and giving me the below error:
Failed to insert into MySQL table 1146 (42S02): Table 'fx003.'aud-cad_30mins'' doesn't exist
aud-cad_30mins table does exist and an insert query like below doing its job:
mySql_insert_query = """INSERT INTO aud-cad_30mins (date, trend) VALUES ( "2021-09-24 21:00:00","Short" )"""
So when I try to use variables in the query, it gives the error. Why the table name getting unwanted quotes? Checked several tutorials but couldn't find a solution, any ideas?
The table name should be hardcoded in the query string instead of having it there as a placeholder %s, which is meant for the values to be inserted. So if you have the table name in the variable, you can replace it via format() before calling cursor.execute()
dbtable = stockname + timeframe
mySql_insert_query = """INSERT INTO {} (date, trend) VALUES ( %s, %s )""".format(dbtable)
see the examples in the docs
edit: as Bill mentioned in the comment, dont add the backticks around the %s placeholders.

How to solve that execute() takes no keyword arguments

I want to insert data to database table with these python 3 script,
cursor = db.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
values = [
("Doni", "Jakarta"),
("Ella", "Surabaya"),
("Fani", "Bandung"),
("Galih", "Depok")
]
for val in values:
cursor.execute(sql, params=val)
db.commit()
print("{} data ditambahkan".format(cursor.rowcount))
but I got error type "TypeError: execute() takes no keyword arguments". could someone help solve this error?
You can directly pass the query and values with it in the form of list.
cursor = db.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
values = [
("Doni", "Jakarta"),
("Ella", "Surabaya"),
("Fani", "Bandung"),
("Galih", "Depok")
]
for val in values:
cursor.execute(sql, list(val))
db.commit()
print("{} data ditambahkan".format(cursor.rowcount))
Or you can use executemany to insert all the values at one time.
cursor = db.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
values = [
("Doni", "Jakarta"),
("Ella", "Surabaya"),
("Fani", "Bandung"),
("Galih", "Depok")
]
cursor.executemany(sql, values)
db.commit()
print("{} data ditambahkan".for

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()

Can't insert single column value in python using MySQL

I have a single column table. I need to insert values in this column. The program runs correctly without errors. But when I check the database, nothing gets inserted. When I added another column to the code and table, the program inserts data correctly. Can you tell me how to insert data for a single column table?
This is the single column code that does not insert anything to the table.
import MySQLdb
conn = MySQLdb.connect(host= "localhost",
user="root",
passwd="123",
db="dbname")
cursor = conn.cursor()
x=100
try:
sql="""INSERT INTO table (col1) VALUES ('%s')"""
cursor.execute(sql, (x))
conn.commit()
except:
conn.rollback()
conn.close()
This is the two columns code.
import MySQLdb
conn = MySQLdb.connect(host= "localhost",
user="root",
passwd="123",
db="dbname")
cursor = conn.cursor()
x=100
y=2
try:
sql="""INSERT INTO table (col1,col2) VALUES ('%s','%s')"""
cursor.execute(sql, (x,y))
conn.commit()
except:
conn.rollback()
conn.close()
You need to lose the quotes around %s, after that you need to know that the second argument to cursor.execute() is a tuple, and that a one-tuple is written:
(item,)
note the comma. The solution is then:
sql="""INSERT INTO table (col1) VALUES (%s)"""
cursor.execute(sql, (x,))
You can try either of these:
Don't use '%s', you can use ? instead
Instead of '%s', just use %s without quotes
try this:
sql="""INSERT INTO table (col1) VALUES ({});""".format(x)
cursor.execute(sql)

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)))

Categories

Resources