How to write proper MySQL Insert statement in Python? - 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()

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.

Use table names as sql parameters in python [duplicate]

I have a syntax error in my python which which stops MySQLdb from inserting into my database. The SQL insert is below.
cursor.execute("INSERT INTO %s (description, url) VALUES (%s, %s);", (table_name.encode("utf-8"), key.encode("utf-8"), data[key].encode("utf-8")))
I get the following error in my stack trace.
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your
SQL syntax; check the manual that corresponds to your MariaDB server
version for the right syntax to use near ''four' (description, url) VALUES ('', 'http://imgur.com/a/V8sdH')' at line 1")
I would really appreciate assistance as I cannot figure this out.
EDIT:
Fixed it with the following line:
cursor.execute("INSERT INTO " + table_name + " (description, url) VALUES (%s, %s);", (key.encode("utf-8"), data[key].encode("utf-8")))
Not the most sophisticated, but I hope to use it as a jumping off point.
It looks like this is your SQL statement:
cursor.execute("INSERT INTO %s (description, url) VALUES (%s, %s);", (table_name.encode("utf-8"), key.encode("utf-8"), data[key].encode("utf-8")))
IIRC, the name of the table is not able to be parameterized (because it gets quoted improperly). You'll need to inject that into the string some other way (preferably safely -- by checking that the table name requested matches a whitelisted set of table names)... e.g.:
_TABLE_NAME_WHITELIST = frozenset(['four'])
...
if table_name not in _TABLE_NAME_WHITELIST:
raise Exception('Probably better to define a specific exception for this...')
cursor.execute("INSERT INTO {table_name} (description, url) VALUES (%s, %s);".format(table_name=table_name),
(table_name.encode("utf-8"),
key.encode("utf-8"),
data[key].encode("utf-8")))

MySQL Python creating table with variable as name

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}

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

Using pymssql to insert datetime object into SQL Server

How do I insert a datatime object using pymssql? I know that the SQL Server table is expecting a datetime object, let's say in position 3. I've tried all three of these:
cursor.execute("INSERT INTO MyTable VALUES(1, 'Having Trouble', datetime.datetime.now())")
cursor.execute("INSERT INTO MyTable VALUES(1, 'Having Trouble', 20130410)")
cursor.execute("INSERT INTO MyTable VALUES(1, 'Having Trouble', '20130410')")
cursor.execute("INSERT INTO MyTable VALUES(1, 'Having Trouble', GETDATE())")
and I get the same error each time:
OperationalError: (241, 'Conversion failed when converting date and/or time from character string.DB-Lib error message 241, severity 16:\nGeneral SQL Server error: Check messages from the SQL Server\n')
I've scoured the little documentation there is, and searched repeatedly.
EDIT: Secondary problem was a field-length problem. See the first comment on the accepted answer.
you are trying to insert a string that is not formated as date (datetime.datetime.now(), 20130410, '20130410', GETDATE()) so sql server can't parse date from it...
so try this...
cursor.execute("
INSERT INTO MyTable
VALUES(
1,
'Having Trouble',
'" + str(datetime.datetime.now()) + "'
)
")
You can use this code:
# a tuple with the data to be stored in db
data = (1, 'Having Trouble', datetime.datetime.now())
# perform the query
cursor.execute("INSERT INTO MyTable VALUES(%s, %s, %s)" % data)
Try this out:
timeStamp = str(datetime.datetime.now())[0:-3]
This time stamp format can be converted by MS SQL SERVER and can be used in pymssql to insert an object of type datetime
For others facing this same issue my problem was different.
My year was getting parsed as 0014; which I thought was being interpreted as 2014. Took me a while to realize what was happening.
Where pymssql comes in is that the smalldate type didn't recognize 0014 as a year and was unable to make the conversion.

Categories