SQLite3 and python not inserting rows - python

I'm trying to insert a row into my table. I've been following the documentation here: https://docs.python.org/2/library/sqlite3.html I get the error: sqlite3.OperationalError: no such column: asd. asd is the value i entered for scholarship name. Heres my code:
conn = sqlite3.connect('pathfinder.db')
c = conn.cursor()
c.execute("INSERT INTO %s VALUES (%s, %s, %s, %s, %s, %s, %s)" % (table, request.form['scholarship_name'],request.form['scholarship_gpa'],request.form['scholarship_amount'], "Male",request.form['specific_essay'], "[]","[]"))

Consider parameterization which is advised in the very link you are following:
# Never do this -- insecure!
symbol = 'RHAT'
c.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol)
String interpolated SQL statements especially with user input from flask requests can potentially be dangerous to your database. Therefore, consider using the second argument of execute that binds values to placeholders, ?, in prepared statement.
# PREPARED STATEMENT
sql = "INSERT INTO {} VALUES (?, ?, ?, ?, ?, ?, ?)".format(table)
# QUERY EXECUTION
c.execute(sql, (request.form['scholarship_name'],
request.form['scholarship_gpa'],
request.form['scholarship_amount'],
"Male",
request.form['specific_essay'],
"[]",
"[]")
)

Related

importing values of a python dictionary as data to an existing mysql table

I have problem with storing values of a python dictionary as data to an existing mysql table
I tried to use the code below but it's not working.
db = mysql.connect(
host="localhost",
user="root",
passwd="123456",
database="tgdb"
)
cursor = db.cursor()
val = ', '.join("'" + str(x) + "'" for x in dict.values())
sql = "INSERT INTO tgdb.channel(user_name, image_url, name,
number_of_members, description, channel_url) VALUES (%s, %s, %s, %s, %s,
%s)"
cursor.execute(sql, val)
db.commit()
print(cursor.rowcount, "record inserted.")
"you have an error in your SQL syntax"
As writed #Torxed shouldn't translate dict in string, you can write just that:
cursor.execute(sql, list(dict.values())

mysql.connector in python / cursor in for-loop only working for first row of table

I have a table and I want to translate columns 'topic' and 'review' of a row and store the entire table with their translations into a new table. It seems that the for-loop doesn't iterate over all rows of the input table. Only the first row is stored into the new table. Why?
database = mysql.connector.connect(user='root', password='root', host='localhost', database='test')
DBcursor = database.cursor(buffered=True)
query = ("SELECT * FROM test_de")
DBcursor.execute(query)
for (id, user_name, date, country, version, score, topic, review, url) in DBcursor:
topic_trans = translate(topic, 'en')
review_trans = translate(review, 'en')
add_translation = ("INSERT INTO test_de_en(id, user_name, date, country, version, score, topic, review, url)"
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)")
translation_data = (id, user_name, date, country, version, score, topic_trans, review_trans, url)
DBcursor.execute(add_translation, translation_data)
database.commit()
DBcursor.close()
database.close()

Postgresql insert data error when using python

I am trying to insert data to the table that was created earlier using python script. Here is the code I am trying to execute. I want to insert data into table with date as well.
date_today = dt.date.today()
conn = psycopg2.connect(host = serverip, port = port, database = database, user = uid, password = pwd)
cursor = conn.cursor()
cursor.execute("INSERT INTO My_TABLE (Date, Class, Total_students, failed_students, Percent_passed_students) VALUES (date_today, 'Class Name', int1, int2, int3)")
print "Data Inserted successfully"
conn.commit()
conn.close()
Here is the error I see from my job. what am i missing here?
psycopg2.ProgrammingError: column "date_today" does not exist
I created the table using different job with the following query:
cursor.execute("""CREATE TABLE MY_TABL(Date date, Lob varchar(30), Total_Students int, failed_students int, Percent_passed_students int)""")
And the table is created with above five columns.
This line:
cursor.execute("INSERT INTO My_TABLE (Date, Class, Total_students, failed_students, Percent_passed_students) VALUES (date_today, 'Class Name', int1, int2, int3)")
Is the incorrect way to dynamically insert values into a database.
Here's a functional and correct example:
cursor.execute("INSERT INTO table VALUES (%s, %s, %s)", (var1, var2, var3))
And applying it in your case...
cursor.execute("INSERT INTO My_TABLE VALUES (%s, %s, %s, %s, %s)", (date_today, 'Class Name', int1, int2, int3))

python dynamic input, update table

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.

Python SQLITE insert into not working

So I am trying to get a simple program to insert information into a sqlite db.
The line that is breaking is the cur.execute
sitename = "TEST sitename2"
siteusername = "TEST siteusername2"
sitepasswd = "TEST sitepassword2"
cur.execute("INSERT INTO mytable(sitename, siteusername, sitepasswd) VALUES(%s, %s, %s)", (sitename, siteusername, sitepasswd))
Error that I receive from Python:
sqlite3.OperationalError: near "%": syntax error
You simply have the wrong parameter style.
>>> import sqlite3
>>> sqlite3.paramstyle
'qmark'
Change your code to:
cur.execute("""INSERT INTO mytable(sitename, siteusername, sitepasswd)
VALUES (?, ?, ?)""", (sitename, siteusername, sitepasswd))

Categories

Resources