Python variables in MySQL: INSERT INTO %s - python

This question has been asked bevor (here), but no answer is working for me and unfortunally I am not allowed to add a comment, because I'm new here.
I didn't know what else to do than asking the question again, sorry for this - please tell me the right way to do.
I want to insert Python variables into a MySQL table named by a Python variable.
I figured out, to create the table by:
curs.execute ("""CREATE TABLE IF NOT EXISTS %s LIKE table""" %(today))
I also figured out to insert values like this:
curs.execute (
""" INSERT INTO table (column)
VALUES (%s) """,
(variable))
Now I tried
today = "table_name"
variable = "name"
curs.execute (
""" INSERT INTO %s (column)
VALUES (%s) """,
( table, variable ))
I'll get this error:
(1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''table_name' (column …' at line 1")
I also tried:
today = "table_name"
variable = "name"
curs.execute (
""" INSERT INTO %s (column)
VALUES (%s) """
% ( table, variable ))
I'll get this error:
(1054, "Unknown column 'name' in 'field list'")
I guess there's something wrong with the strings …
Thank you for answers!

Try replacing the %s with ? and let sqlite handle the insertion. (Also helps preventing SQL injection attacks in web applications)
table_name = "today"
variable = "name"
curs.execute ("INSERT INTO ? (column) VALUES (?)",(table_name, variable))

Try:
today = "table_name"
variable = "name"
curs.execute (
""" INSERT INTO :table_name (column)
VALUES (:variable_name) """,
{'table_name': today, 'variable_name': variable})

You have muddled your variables in your third, not working code snippet. instead try:
table_name = "today"
variable = "name"
curs.execute (
""" INSERT INTO %s (column)
VALUES (%s) """,
( table_name, variable ))
This will create a table named 'Today' with one column named 'column' with one data value in it 'name'.
For this to work you will need to have previously created a table that has this column available.
So your create code needs to change:
"""create table "today" ("column" varchar2(16BYTE), *add extra columns here if you wish*)"""

Related

Not all parameters were used in the SQL statement error

I would like to get names from one db and initiate a new table with it. I want to add more analysis, but this is my starting point where I'm already struggling and I have no idea where I made the mistake.
mydb = db_login()
# get team
team = pd.read_sql('SELECT * FROM team', con=mydb)
names = team.name.to_list()
this will output something like ['name1', 'name2' ...]
mycursor = mydb.cursor()
mycursor.execute("DROP TABLE IF EXISTS team_analyse")
mycursor.execute("CREATE TABLE team_analyse (name VARCHAR(50))") #todo add all needed columns
sqlFormula = "INSERT INTO team_analyse (name) VALUES (%s)" #todo initial team commit
mycursor.executemany(sqlFormula, names)
mydb.commit()
In the end I get the following error:
mysql.connector.errors.ProgrammingError: Not all parameters were used in the SQL statement
You should be using a single INSERT INTO ... SELECT here:
INSERT INTO team_analyse (name)
SELECT name
FROM team
Your updated Python script:
mycursor = mydb.cursor()
sql = """INSERT INTO team_analyse (name)
SELECT name
FROM team"""
mycursor.execute(sql)
The error message you are seeing is telling you that you passed a list as the parameters to bind to the statement, but not all parameters were used. Actually, the single insert statement you were trying to run only has a single parameter. But in any case, it is unnecessary to bring the result set from the team table into Python's memory. Instead, use my suggestion and let MySQL do the heavy lifting.

Error selecting from sql table using mysql placeholders

I am trying to select some values within a table that has a column called "Name". That column contains tennis players names. I want to store some statistics for each player in python, but I am having trouble accessing the table. I keep getting a "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '='Rafael Nadal'' at line 1" As you can see, mysql clearly interprets the %s I had in place of 'Rafael Nadal' correctly, but it still brings up an error. Can anyone help me?
recordTuple = ('Rafael Nadal', )
mySql_insert_query = """SELECT `First_Serve(%)` FROM `serve2` WHERE Name =%s"""
cursor.execute(mySql_insert_query, recordTuple)
aI = cursor.fetchall()[0][0]/100
Since % is used to mark placeholders in the SQL, you have to double it if you want to use it literally.
mySql_insert_query = """SELECT `First_Serve(%%)` FROM `serve2` WHERE Name =%s"""
See How do I escape % from python mysql query

Unexpected TIMESTAMP format in SQL Server

I'm trying to populate my time column which is a TIMESTAMP datatype with an INSERT command from my Python script. This is my current code for the insert:
usercount= ("INSERT INTO UserNum(Amount, Network) \
VALUES ('%s', '%s')" % \
(num_user, nets_id["name"]))
I haven't included to insert a TIMESTAMP value as I believe this gets automatically generated upon INSERT
But when I look at the UserNum table the time column is populated by values such as AAAAAAAAE5U= is there something I'm doing wrong?
Any help with this would be much appreciated!
You do not need to make your arguments strings. Python handles it.
Try this:
usercount = "INSERT INTO UserNum(Amount, Network) VALUES (%s, %s)" % (num_user, nets_id["name"])
but be sure that they are of the same type as in your DB.

Getting column is of type jsonb[] but expression is of type text[] when trying to insert with psycopg2

I'm using execute_values to insert the content of many tables on other tables, I already set the adapter of dict to json when I received other error, however I don't know how to treat this one:
psycopg2.ProgrammingError: column "rules" is of type jsonb[] but expression is of type text[]
LINE 1: ...UES (1,'tturxvrtgvvsrqgzsedcoyqujakyepjordrbbjdw',ARRAY['{"i...
The only way to handle that was something like this issue, but I would need to treat each column ...
Maybe there are ways to create a new adapter, but I couldn't achieve how to do that by the docs.
register_adapter(dict, Json)
execute_values(
dest_cursor,
f'''
INSERT INTO {t} VALUES %s ON CONFLICT DO NOTHING;
''',
records,
)
Is there a automatic way to deal with that, like the register_adapter?
I've found the answer by this issue I learned I could use the template parameter, like so:
execute_values(
dest_cursor,
f'''
INSERT INTO {t} VALUES %s ON CONFLICT DO NOTHING;
''',
records,
template="(%s, %s, %s::jsonb[], %s, %s)" # as many placeholders requested
)

sqlite3 python adding columns and updating values

I am learning how to use sqlite3 in python. I have a simple table with 2 columns: ID and name.
I tried adding a new column to this table using the following commands (I am working in ipython):
conn = sqlite3.connect('mydatabase.db')
c = conn.cursor()
c.execute("alter table studentinfo add column Group integer")
I get the following error:
OperationalError: near "Group": syntax error
Then, based on the examples here on S.O. I tried,
c.execute("alter table studentinfo add column 'Group' integer")
This worked. However, I have another problem now. Apparently the column name is "'Group'" instead of just "Group".
For example, when I try to update the value in this column, of the following three commands, one works and two do not.
conn = sqlite3.connect('mydatabase.db')
c = conn.cursor()
c.execute("update studentinfo set Group=1 where ID <= 4") #This did not work.
I get the following error:
OperationalError: near "Group": syntax error
Then I tried to put quotes around column names:
c.execute("update studentinfo set 'Group'=1 where 'ID' <= 4")
#This did not work either. Gives no error, but does not do anything. Records remain
#unchanged.
Then, I tried with quotes around Group but not around ID. This worked fine.
c.execute("update studentinfo set 'Group'=1 where ID <= 4") #This worked fine.
That is, it thinks of the column name as 'Group' (with the quotes). How do I add a column with just the name Group?
Thank you.
When table name or column name is the same as SQL keywords (such as GROUP), errors are generated. You need to quote the table name with ` `, not ' '. So you could use:
alter table studentinfo add column `Group` integer
GROUP is an SQLite keyword.
Resolution: Name your column something else.
The trouble is how you performed the ALTER TABLE command. By including single quotes around the column name you specified that was part of the name. Drop the quotes, and it should work as you expect.
FYI: you can query the schema in sqlite3 with the dot-s command (.s). It will show you the true column names. Here's a quick sample:
SQLite version 3.7.9 2011-11-01 00:52:41
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> create table a( mycol1 INT );
sqlite> alter table a add column mycol2 int;
sqlite> alter table a add column 'mycol3' int;
sqlite> .s
CREATE TABLE a( mycol1 INT , mycol2 int, 'mycol3' int);
sqlite>

Categories

Resources