This question already has answers here:
How to use variables in SQL statement in Python?
(5 answers)
Closed 3 years ago.
Iām setting up a new flask app, and I'm using sqlite3 as DB. It is possible to maintain the setup even if I have to insert 5 values?
def encrypt():
now = datetime.now()
date_time = now.strftime("%d/%m/%Y - %H:%M")
filename = secure_filename(request.form['filename'].replace(" ", "_").replace("(", "").replace(")", ""))
password = request.form['password']
username = session.get('username')
id = request.form['id']
type = infile[-4:]
file = filename[:-4] + '.enc'
infile = os.path.join(app.config['DATA_FOLDER'], filename)
outfile = os.path.join(app.config['DATA_FOLDER'], filename[:-4] + '.enc')
con = sqlite3.connect(app.config['DataBase'])
cur = con.cursor()
cur.executemany('INSERT INTO keys (id, file, type, date_time, attempts) VALUES (?,?,?,?,?)', id, file, type, date_time, "0")
con.commit()
con.close()
return 'ok'
The following error is shown in logs:
File "./myapp.py", line 524, in encrypt
cur.executemany('INSERT INTO keys (id, file, type, date_time, attempts) VALUES (?,?,?,?,?)', id, file, type, date_time, "0")
TypeError: function takes exactly 2 arguments (6 given)
Firstly, you don't need to use executemany as that is used when you want to insert multiple rows into a single table. What you have there is just multiple values that will represent a single row. Use placeholders for the values in the SQL statement, and pass a tuple as the second argument to execute.
cur.execute('INSERT INTO keys (id, file, type, date_time, attempts) VALUES (?, ?, ?, ?, ?)', (id, file, type, date_time, "0"))
Bonus answer (the executemany case)
Now, when you want to insert multiple rows in the same table, you'd use the cursor.executemany method. And that takes 2 arguments, like you've found out in your error above:
a string, which represents the SQL query
a collection of parameters, where each parameter is a list of values representing a row
The sql query is executed against all parameters in the collection.
Working example with both execute and executemany that can be pasted in a Python file and run
import sqlite3
conn = sqlite3.connect(':memory:')
cursor = conn.cursor()
cursor.execute('CREATE TABLE person (first_name text, last_name text, age integer)')
cursor.execute('SELECT * FROM person')
print(cursor.fetchall()) # outputs []
first_name, last_name, age = 'Carl', 'Cox', 47
cursor.execute('INSERT INTO person (first_name, last_name, age) VALUES (?, ?, ?)', (first_name, last_name, age))
cursor.execute('SELECT * FROM person')
print(cursor.fetchall()) # outputs [('Carl', 'Cox', 47)]
many_values = [
('Boris', 'Brejcha', 37),
('Mladen', 'Solomun', 43),
]
cursor.executemany('INSERT INTO person (first_name, last_name, age) VALUES (?, ?, ?)', many_values)
cursor.execute('SELECT * FROM person')
print(cursor.fetchall()) # outputs [('Carl', 'Cox', 47), ('Boris', 'Brejcha', 37), ('Mladen', 'Solomun', 43)]
conn.close()
So you see in the executemany case how the method takes just 2 parameters, but the 2nd parameter is a sequence of sequences.
Related
I want to insert variable values into db2 table using Python code
id = input("table id: ")
tabname = input("Enter Table name: ")
descr = input("Enter description : ")
inser_sql = "INSERT INTO schema.table VALUES (?, ?, ?)",(id, tabname, descr)
stmt = ibm_db.prepare(conn, inser_sql)
ibm_db.execute(stmt)
this code gives me error:
stmt = ibm_db.prepare(conn, inser_sql)
Exception: statement must be a string or unicode
Assuming that your table is defined like this:
"create table myschema.mytable(id int, tabname varchar(10), description varchar(10))"
I understand your intention is to insert a specific row into it with a prepared statement and parameter markers.
Skipping the input part:
In [14]: id = 1
In [15]: tabname = 'TAB'
In [16]: descr = 'my desc'
you just need to prepare the statement first, bind the parameters later and then execute:
insert_sql = "INSERT INTO myschema.mytable VALUES (?, ?, ?)"
prep_stmt = ibm_db.prepare(conn, insert_sql)
ibm_db.bind_param(prep_stmt, 1, id)
ibm_db.bind_param(prep_stmt, 2, tabname)
ibm_db.bind_param(prep_stmt, 3, descr)
ibm_db.execute(prep_stmt)
The exact answer will depend on the specific DB2 library you're using, but the variable holding your query should just be a plain string.
You will probably need to pass parameters to it when you execute the statement:
inser_sql = "INSERT INTO schema.table VALUES (?, ?, ?)"
stmt = ibm_db.prepare(conn, inser_sql)
ibm_db.execute(stmt, (id, tabname, descr))
# ^^^^^^^^^^^^^^^^^^^^
I am getting the error 'sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 4, and there are 1 supplied.' The below code should be making a database and creating a table with the the titles listed below. Then take values from a csv. file and add it under the allotted headings. Any help would be would be appreciated!
import const
import sqlite3
SEP = ','
DATA_FILENAME = 'pokemon.csv'
con = sqlite3.connect('poki.db')
cur = con.cursor()
cur.execute('DROP TABLE IF EXISTS poki')
cur.execute( ' CREATE TABLE poki( pokemon TEXT, species_id INTEGER,'
' height REAL, weight REAL)' )
values = ('INSERT INTO poki VALUES (?, ?, ?, ?)')
for line in DATA_FILENAME:
list_of_values = line.strip().split(SEP)
cur.execute(values, list_of_values)
cur.close()
con.commit()
con.close()
I have a Python string (or potentially a Python dictionary) that I'd like to insert to MySql table.
My String is the following:
{'ticker': 'BTC', 'avail_supply': 16479075.0, 'prices': 2750.99, 'name': 'Bitcoin', '24hvol': 678995000.0}
I have the same kind of error if I want to insert the Dict format.
I really don't understand this kind of error (i.e. the '\' in-between the components of the string).
How can I deal with this error? Any why to properly insert a whole string to a particular TEXT cell in SQL?
Many thanks !!
Here is how to connect, make a table, and insert in the table.
import MySQLdb as mdb
import sys
#connect
con = mdb.connect('localhost', 'testuser', 'test623', 'testdb');
with con:
#need the cursor object so you can pass sql commands, also there is a dictionary cursor
cur = con.cursor()
#create example table
cur.execute("CREATE TABLE IF NOT EXISTS \
Writers(Id INT PRIMARY KEY AUTO_INCREMENT, Name VARCHAR(25))")
#insert what you want
cur.execute("INSERT INTO Writers(Name) VALUES('Jack London')")
cur.execute("INSERT INTO Writers(Name) VALUES('Honore de Balzac')")
cur.execute("INSERT INTO Writers(Name) VALUES('Lion Feuchtwanger')")
cur.execute("INSERT INTO Writers(Name) VALUES('Emile Zola')")
cur.execute("INSERT INTO Writers(Name) VALUES('Truman Capote')")
Example above will make a table with 2 cols, one ID and one name
look here on an example on how to insert stuff from dictionary with keys and list as value to sql, basically you need place holders
sql = "INSERT INTO mytable (a,b,c) VALUES (%(qwe)s, %(asd)s, %(zxc)s);"
data = {'qwe':1, 'asd':2, 'zxc':None}
conn = MySQLdb.connect(**params)
cursor = conn.cursor()
cursor.execute(sql, data)
cursor.close()
conn.close()
or you can go with this as an example for a simple straight forward dict
placeholders = ', '.join(['%s'] * len(myDict))
columns = ', '.join(myDict.keys())
sql = "INSERT INTO %s ( %s ) VALUES ( %s )" % (table, columns, placeholders)
cursor.execute(sql, myDict.values())
having trouble with these two functions
was wondering if people could tell me where I am going wrong
this is a separate function as part of a spider that searches through a website of house prices
def save_house_to_db(id, address, postcode, bedrooms):
conn = sqlite3.connect('houses_in_london.db')
d = conn.cursor()
d.execute('INSERT INTO TABLE houses (id, address, postcode, bedrooms) VALUES (%d %s %s %d)' %(id, str(address), str(postcode), float(bedrooms)))
d.commit()
d.close()
def save_transactions_to_db(id, sale_price, date):
conn = sqlite3.connect('houses_in_london.db')
d = conn.cursor()
d.execute('INSERT INTO TABLE transactions (transaction_id NOT NULL AUTO_INCREMENT, house_id, date, sale_price) VALUES'
'(%d %s %s)' %(id, sale_price, str(date)))
d.commit()
d.close()
here is the error raised:
Traceback (most recent call last):
File "/Users/saminahbab/Documents/House_Prices/final_spider.py", line 186, in <module>
final_function(link_set=areas,id_counter=40)
File "/Users/s/Documents/House_Prices/final_spider.py", line 158, in final_function
page_stripper(link=(root+page), id_counter=id_counter)
File "/Users/s/Documents/House_Prices/final_spider.py", line 79, in page_stripper
save_house_to_db(id=float(id_counter), address=address, postcode=postcode, bedrooms=bedrooms)
File "/Users/s/Documents/House_Prices/final_spider.py", line 25, in save_house_to_db
d.execute('INSERT INTO TABLE houses VALUES (%d %s %s %d)' %(id, str(address), str(postcode), float(bedrooms)))
sqlite3.OperationalError: near "TABLE": syntax error
and for reference here is the execute for the databse
# conn = sqlite3.connect('houses_in_london.db')
# database = conn.cursor()
# database.execute('CREATE TABLE houses (id INTEGER PRIMARY KEY, address TEXT,'
# 'postcode TEXT, bedrooms TEXT)')
#
# database.execute('CREATE TABLE transactions (transaction_id NOT NULL AUTO_INCREMENT, house_id INTEGER '
# ' REFERENCES houses(id), date TEXT, sale_price INTEGER )')
as always, thank you for the support
You have many issues:
INSERT-clause has no TABLE keyword
You're trying to pass variables to an SQL query using string formatting; don't do it, ever ā use placeholders, or face the consequences
Your VALUES-clause is missing commas between the value-expressions
The sqlite3 module uses "?" as a placeholder instead of percent formatters
"transaction_id NOT NULL AUTO_INCREMENT" is not a valid column name
"AUTO_INCREMENT" is not valid SQLite syntax and you probably meant for transaction_id to be INTEGER PRIMARY KEY ā also AUTOINCREMENT should usually not be used
The below functions fix some of the errors, barring the DDL-corrections to the transactions table.
def save_house_to_db(id, address, postcode, bedrooms):
conn = sqlite3.connect('houses_in_london.db')
d = conn.cursor()
# Remove the TABLE "keyword"
d.execute('INSERT INTO houses (id, address, postcode, bedrooms) '
'VALUES (?, ?, ?, ?)', (id, address, postcode, bedrooms))
d.commit()
d.close()
def save_transactions_to_db(id, sale_price, date):
conn = sqlite3.connect('houses_in_london.db')
d = conn.cursor()
# This here expects that you've fixed the table definition as well
d.execute('INSERT INTO transactions (house_id, date, sale_price) '
'VALUES (?, ?, ?)', (id, sale_price, date))
d.commit()
d.close()
I wrote a program in order to dynamically update a database table but I am getting an error. I stuffed the program with whatever I know little about. Here's my code:
import MySQLdb
class data:
def __init__(self):
self.file123 = raw_input("Enter film: ")
self.title_ = raw_input("Enter film: ")
self.year = raw_input("Enter year: ")
self.director = raw_input("Enter director: ")
a=data()
db = MySQLdb.connect(host="localhost", # your host, usually localhost
user="root", # your username
passwd="mysql", # your password
db="sakila") # name of the data base
cursor = db.cursor()
cursor.execute("INSERT INTO films (file123, title_, year, director) VALUES (?, ?, ?, ?)", (a.file123, a.title_, a.year, a.director))
db.commit()
db.close()
This is the error:
File "C:\Python27\maybe1.py", line 20, in <module>
cursor.execute("INSERT INTO films (file123, title_, year, director) VALUES (?, ?, ?, ?)", (a.file123, a.title_, a.year, a.director))
File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 184, in execute
query = query % db.literal(args)
TypeError: not all arguments converted during string formatting
How can I fix this issue ?
You should change ? to %s.
Here is question about why mysqldb use %s instead of ?.
I would do it this way:
query = "INSERT INTO films (file123, title_, year, director) VALUES (%s, %s, %s, %s)" % (a.file123, a.title_, a.year, a.director)
cursor.execute(query)
Replace %s with correct data type, else it will try everything as string which might break at table level.