MySQL Python creating table with variable as name - python

I am working on a project with a friend and am new to sql databases. I want to have a database with tables named after the date they were created. I have tried multiple things but i thought .format() would be the best, but it didnt work. This is how it currently looks:
today = date.today()
d1 = today.strftime("%b-%d-%Y")
sql = "CREATE TABLE {table} (CEO VARCHAR(255), profits INTEGER(10))"
mycursor.execute(sql.format(table = d1))
i am also trying to insert into the database with .format:
sql = "INSERT INTO{table} (CEO, profits) values (%s, %s)"
mycursor.execute(sql.format(table = d1), (Company(c).get_CEO(), int(Company(c).get_profit())))
mydb.commit()
I get the error:
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax;

You have no space between INTO and {table}

Related

I was trying to run MySQL query using Python but getting error 1064 (42000):

import mysql.connector as connection
try:
mydb = connection.connect(host="localhost", database = 'motogp',user="root", passwd="unlock24708651",use_pure=True)
# check if the connection is established
print(mydb.is_connected())
query = "CREATE TABLE Riders_championship(Rank INT(3), Rider_name CHAR(20), Nation CHAR(12), Team VARCHAR(20), Points INT(3))"
cursor = mydb.cursor() #create a cursor to execute queries
cursor.execute(query)
print("Table Created!!")
mydb.close()
except Exception as e:
mydb.close()
print(str(e))
ERROR:
True
1064 (42000): 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 'Rank INT(3), Rider_name CHAR(20), Nation CHAR(12), Team VARCHAR(20), Points INT(' at line 1
RANK is a reserved keyword in MySQL, well, at least on v8.0.2 and above. If you want to stick with using it, then you have to wrap it in backticks like:
query = "CREATE TABLE Riders_championship(`Rank` INT(3), Rider_name CHAR(20), Nation CHAR(12), Team VARCHAR(20), Points INT(3))"
And on all your future codes. So doing a SELECT like:
SELECT Rank FROM Riders_championship;
Will return you the same error that you're getting now, therefore you have to write it like:
SELECT `Rank` FROM Riders_championship;
for it to work. Same goes for all your INSERT, UPDATE, DELETE queries.
Here's a simple demo to show you.
I personally won't prefer using keywords even if it's reserved or not so if it's me, I might rename my column to RANKS instead. That way it won't clash with the reserved keyword.

How to write proper MySQL Insert statement in Python?

I am trying to insert two columns of data into a MySQL table from Python. And my Insert statement is true, I guess. But I am still getting 1064 error code.
This is for MySQL server version 8.0.12 and Python 3.7. I had tried changing different methods of inserting dynamic variables.
#alter is the data value read from serial port
sql="select * from stds"
cur.execute(sql)
records=cur.fetchall()
if cur.rowcount>0:
print('Number of rows - ',cur.rowcount)
else:
print('No data in table')
for row in records:
print(row)
if row[1]==alter:
print("Student exists : ",row[1])
date = datetime.datetime.now()
print(type(date))
ins = (alter, date)
sql = "Insert into 'attendance' ('stdid', 'dt') VALUES (%s,%s)"
cur.execute(sql, ins)
cnn.commit()
print('Sucessfully Stored the Record')
#success(alter)
break
else:
print("Student doesn't exist")
I am getting this error message
Error:
mysql.connector.errors.ProgrammingError: 1064 (42000): 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 ''attendance' ('stdid', 'dt') VALUES ('FE0070E83D5B','2019-08-01 09:09:06.162304'' at line 1
And I am expecting that these read tag values are inserted successfully​.
Identifiers (e.g. column and table names) in MySQL (and most other flavors of SQL as well) do not take single quotes. They take either no quotes, double quotes, or maybe backticks in the case of MySQL. Try this version:
sql = "INSERT INTO attendance (stdid, dt) VALUES (%s, %s)"
ins = (alter, date)
cur.execute(sql, ins)
cnn.commit()

mysql.connector.errors.ProgrammingError: Error in SQL Syntax

I'm using the Python MySQL connector to add data to a table by updating the row. A user enters a serial number, and then the row with the serial number is added. I keep getting a SQL syntax error and I can't figure out what it is.
query = ("UPDATE `items` SET salesInfo = %s, shippingDate = %s, warrantyExpiration = %s, item = %s, WHERE serialNum = %s")
cursor.execute(query, (info, shipDate, warranty, name, sn, ))
conn.commit()
Error:
mysql.connector.errors.ProgrammingError: 1064 (42000): 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 'WHERE serialNum = '1B0000021A974726'' at line 1
"1B0000021A974726" is a serial number inputted by the user and it is already present in the table.
No , before the WHERE statement

Python insert variable to mysql via mysql.connector

I am trying to create one python script to insert data into mysql, but I got an error when I try to test it.
This is how I create the table:
CREATE TABLE aaa (
id MEDIUMINT NOT NULL AUTO_INCREMENT,
data CHAR(30) NOT NULL,
PRIMARY KEY (id)
);
This is my python script:
import mysql.connector
from time import strftime, gmtime, sleep
cnx = mysql.connector.connect(
user='root', password='abcd', database='test_db'
)
cur = cnx.cursor()
# get current timestamp
curr_time = strftime("%Y%m%d_%H%M%S", gmtime())
cur.execute(
"INSERT INTO aaa(data) VALUES (%s)", (curr_time)
)
cnx.commit()
cnx.close()
The error is like this:
mysql.connector.errors.ProgrammingError: 1064 (42000): 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 '%s)' at line 1
Can anyone help me solve this problem?
replace , with % in "INSERT INTO aaa(data) VALUES (%s)", (curr_time) it should be "INSERT INTO aaa(data) VALUES (%s)"%(curr_time).
#tsh is correct use this (curr_time) -> (curr_time,) instead

Dynamic table names within MYSQL statement (Google Cloud SQL)

I am trying to drop/delete a table from within Google Cloud SQL using Python (App Engine) but I want the table name to be based on a variable, for simplicity I am using 'hello' here. For some reason it is throwing back an error at me: "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 '-IN' at line 1"
I tried the following:
tabNameShort = 'hello'
cursor = conn.cursor()
cursor.execute('DROP TABLE IF EXISTS %s', (tabNameShort))
conn.commit()
I also tried:
tabNameShort = 'hello'
cursor = conn.cursor()
cursor.execute('DROP TABLE IF EXISTS ' + tabNameShort)
conn.commit()
Any suggestions?
try this:
tabNameShort = 'hello'
cursor = conn.cursor()
cursor.execute('DROP TABLE IF EXISTS `%s`' % tabNameShort)
conn.commit()
A warning: appending the table name directly using '+' can result in an SQL injection vulnerability, if the table name is derived, directly or indirectly, from user input.

Categories