Python & PostgreSQL: Function to insert variable arg into table? - python

I am trying to do the code as follows to register a player with a given name, but I can't get the argument name to do anything… I thought that %s was the variable to insert a string into a database, but it doesn't seem to work.
import psycopg2
def registerPlayer(name):
"""Registers new player."""
db = psycopg2.connect("dbname=tournament")
c = db.cursor()
c.execute("insert into Players values (%s);")
db.commit()
db.close()
registerPlayer("Butter")
When I run it, I get the error message:
ProgrammingError: syntax error at or near "%"
LINE 1: insert into Players values (%s);

You haven't actually passed the parameter into the execute method.
c.execute("insert into Players values (%s);", (name,))

Related

Variable Input not inserting into SQLite3

i'm a bit of an amateur IT Professional who has been getting to grips with Python and Django. This query is just for Python and SQLite3.
So I have the following code, which is meant to take an input from the user, and then pass it to a function I have created.
from dbadd import inputdetails
import sqlite3
conn = sqlite3.connect('torndata.db')
c = conn.cursor()
print('Enter Name')
u_name = str(input())
print('Enter Age')
u_age = int(input())
print('Enter Gender')
u_gender = str(input())
inputdetails(u_name, u_age, u_gender)
conn.close()
And this is the function it is calling:
import sqlite3
conn = sqlite3 . connect ( 'torndata.db' )
cursor = conn.cursor ()
def inputdetails(u_name,u_age,u_gender):
cursor.execute("""
INSERT INTO userdata(name, age, gender)
VALUES (?,?,?)
""", (u_name, u_age, u_gender))
conn.commit()
I get no errors when it runs, but when I run the following, it shows no data has been moved to the table I have specified.
c.execute("SELECT * FROM userdata")
print(c.fetchall())
conn.commit()
conn.close()
The database is already created within SQLite3 and the table has been set up, I can query it directly.
Bad indent. The commit statement is not part of the function.

Python/MySQL: Using %s in a pythonic manner instead of a mysql.connector manner in an INSERT statement

I am trying to write a script that reads a tab delimited text file and first creates a mysql table and then inserts the data into that table.
Problem: I'm stuck on writing the INSERT query because %s placeholder serves a new purpose with the mysql.connector API. Here is my code:
def insertmanyquery(tabletitle, headers, values):
'''connects to a mysql database and inserts a list of tab delimited rows into a table'''
cnxn = connect(all the connection parameters)
cursor = cnxn.cursor()
numofvalues = r"%s, " * len(headers.split(','))
numofvalues = numofvalues[:-2]
query = "INSERT INTO %s (%s) VALUES (%s)" % (tabletitle, headers, numofvalues)
cursor.executemany(query,values)
cnxn.commit()
cursor.close()
cnxn.close()
This would hopefully allow the insert query to adapt to however many columns are present in the table.
If I call the function as follows:
tabletitle = 'Bikes'
headers = 'BikeBrand, BikeName, Purpose, Price, YearPurchased'
values = ['Norco', 'Range', 'Enduro', 8,000.00, 2018]
insertmanyquery(tabletitle, headers, values)
I get the following error: mysql.connector.errors.ProgrammingError: Not all parameters were used in the SQL statement
If I just print the query instead of executing it, it looks fine:
INSERT INTO Bikes (BikeBrand, BikeName, Purpose, Price, YearPurchased) VALUES (%s, %s, %s, %s, %s)
I believe I am getting this error because the third %s in my INSERT query is being interpreted as a part of the connector INSERT syntax instead of first being interpreted in a pythonic manner and then being interpreted as connector syntax.
I am very new to coding so maybe I'm approaching this all wrong, regardless, I'd like to hear potential solutions to this problem or better ways to code this.
Thank you for your time
UPDATE:
I have tried making the query query = "INSERT INTO %s (%s)" % (tabletitle, headers) + " VALUES (" + numofvalues +");" and I still get the same error! so it doesn't have to do with using the placeholder.. >.<

Python and MySQL : Error with simple INSERT

import mysql.connector
conn = mysql.connector.connect(host="localhost",user="root",password="password", database="database_name")
cursor = conn.cursor()
a = "abcd"
cursor.execute("INSERT INTO table_jeux (lien_fiche) VALUES (?)", (a))
And this is the error I get when I execute the script :
ProgrammingError: 1064 (42000): Syntax error near to '?)' at line 1
Thanks for help, I really don't understand why.
What You probably want is to insert variable a into Your SQL code, but it doesn't work - and the parser gets a "?" where You want it to have "abcd"
You could try this:
cursor.execute("INSERT INTO table_jeux (lien_fiche) VALUES ({})".format(a))
or (in somewhat python2 manner):
cursor.execute("INSERT INTO table_jeux (lien_fiche) VALUES (%s)", (a,))
as described here:
https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html
Try using f strings,
It should look something like this:
cursor.execute(f'INSERT INTO student (student_name, student_email, courseid) VALUES ("{student_name}","{student_email}",{course_id})')
where student_name, student_email and course_id are all variables.
In your case:
cursor.execute(f'INSERT INTO table_jeux (lien_fiche) VALUES ("{a}")')

unable to insert data that are stored in variables in to an MYSQL database table using python

am trying to insert the data entered into the web form into database table,i am passing the data to the function to insert the data,but it was not successful below is my code
def addnew_to_database(tid,pid,usid,address,status,phno,email,ord_date,del_date):
connection = mysql.connector.connect(user='admin_operations', password='mypassword',host='127.0.0.1',database='tracking_system')
try:
print tid,pid,usid,address,status,phno,email,ord_date,del_date
cursor = connection.cursor()
cursor.execute("insert into track_table (tid,pid,usid,address,status,phno,email,ord_date,del_date) values(tid,pid,usid,address,status,phno,email,ord_date,del_date)")
cursor.execute("insert into user_table (tid,usid) values(tid,usid)")
finally:
connection.commit()
connection.close()
You should pass the variables as an argument to .execute instead of putting them in the actual query. E.g.:
cursor.execute("""insert into track_table
(tid,pid,usid,address,status,phno,email,ord_date,del_date)
values (%s,%s,%s,%s,%s,%s,%s,%s,%s)""",
(tid,pid,usid,address,status,phno,email,ord_date,del_date))
cursor.execute("""insert into user_table
(tid,usid)
values (%s,%s)""",(tid,usid))
You should tell us what API you are using and what the error code is.
You should define the values within the execution, right now within the sql statement as a string they are not referencing anything.
Typically when you use a variable name inside of a sql statement this way, you need to indicate that it is a variable you are binding data to. This might be replacing it with (1,2,3,4..) or (%s,%s,...) that corresponds to an ordered list or using variable names (:tid,:pid,...) that you then define the values of with a dictionary as the second argument of execute().
Like this:
track_table_data = [tid,pid,usid,address,status,phno,email,ord_date,del_date]
user_table_data = [tid,usid]
cursor.execute("insert into track_table (tid,pid,usid,address,status,phno,email,ord_date,del_date) values(1,2,3,4,5,6,7,8,9)", track_table_data)
cursor.execute("insert into user_table (tid,usid) values(1,2)",user_table_data)
or
cursor.execute("insert into track_table (tid,pid,usid,address,status,phno,email,ord_date,del_date) values(:tid,:pid,:usid,:address,:status,:phno,:email,:ord_date,:del_date))", {'tid':tid,'pid':pid,'usid':usid,'address':address,'status':status,'phno':status,'email':email,'ord_date':ord_date,'del_date':del_date})
cursor.execute("insert into user_table (tid,usid) values(:tid,:usid)",{'tid':tid,'usid':usid})

django + south + python: strange behavior when using a text string received as a parameter in a function

this is my first question.
I'm trying to execute a SQL query in django (south migration):
from django.db import connection
# ...
class Migration(SchemaMigration):
# ...
def transform_id_to_pk(self, table):
try:
db.delete_primary_key(table)
except:
pass
finally:
cursor = connection.cursor()
# This does not work
cursor.execute('SELECT MAX("id") FROM "%s"', [table])
# I don't know if this works.
try:
minvalue = cursor.fetchone()[0]
except:
minvalue = 1
seq_name = table + '_id_seq'
db.execute('CREATE SEQUENCE "%s" START WITH %s OWNED BY "%s"."id"', [seq_name, minvalue, table])
db.execute('ALTER TABLE "%s" ALTER COLUMN id SET DEFAULT nextval("%s")', [table, seq_name + '::regclass'])
db.create_primary_key(table, ['id'])
# ...
I use this function like this:
self.transform_id_to_pk('my_table_name')
So it should:
Find the biggest existent ID or 0 (it crashes)
Create a sequence name
Create the sequence
Update the ID field to use sequence
Update the ID as PK
But it crashes and the error says:
File "../apps/accounting/migrations/0003_setup_tables.py", line 45, in forwards
self.delegation_table_setup(orm)
File "../apps/accounting/migrations/0003_setup_tables.py", line 478, in delegation_table_setup
self.transform_id_to_pk('accounting_delegation')
File "../apps/accounting/migrations/0003_setup_tables.py", line 20, in transform_id_to_pk
cursor.execute(u'SELECT MAX("id") FROM "%s"', [table.encode('utf-8')])
File "/Library/Python/2.6/site-packages/django/db/backends/util.py", line 19, in execute
return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: relation "E'accounting_delegation'" does not exist
LINE 1: SELECT MAX("id") FROM "E'accounting_delegation'"
^
I have shortened the file paths for convenience.
What does that "E'accounting_delegation'" mean? How could I get rid of it?
Thank you!
Carlos.
The problem is that you're using DB-API parameterization for things that are not SQL data. When you do something like:
cursor.execute('INSERT INTO table_foo VALUES (%s, %s)', (col1, col2))
the DB-API module (django's frontend for whatever database you are using, in this case) will know to escape the contents of 'col1' and 'col2' appropriately, and replace the %s's with them. Note that there are no quotes around the %s's. But that only works for SQL data, not for SQL metadata, such as table names and sequence names, because they need to be quoted differently (or not at all.) When you do
cursor.execute('INSERT INTO "%s" VALUES (%s, %s)', (tablename, col1, col2))
the tablename gets quoted as if you mean it to be string data to insert, and you end up with, for example, "'table_foo'". You need to separate your SQL metadata, which is part of the query, and your SQL data, which is not, like so:
sql = 'INSERT INTO TABLE "%s" VALUES (%%s, %%s)' % (tablename,)
cursor.execute(sql, (col1, col2))
Note that because the django DB-API frontend's paramstyle is 'pyformat' (it uses %s for placeholders) you need to escape those when you do the string formatting to create the SQL you want to execute. And note that this isn't secure against SQL injection attacks when you take the tablename from an insecure source and don't validate it.

Categories