-1

Hope you are all doing well.

I have been using Python's mysql.connector library for a while. This time I am using it to send/insert 6 different values to the table. However, it seems like I could not figure out the correct syntax to use.

Here is my code:

import mysql.connector
from mysql.connector import Error
import random
import math
import time


try:
    conn = mysql.connector.connect(host='hidden', database = 'lvad', user='hidden', password='hidden') 
    print ("sql connected")
        
except Error as e:
    print (e)

cursor = conn.cursor()  

while True:

    data1 = random.random()
    data2 = 10 * data1
    data3 = math.sin(data2)
    data4 = 0
    data5 = 123.23432324
    data6 = 0.7

    data1 = str(data1)
    data2 = str(data2)
    data3 = str(data3)
    data4 = str(data4)
    data5 = str(data5)
    data6 = str(data6)

    query = f'INSERT INTO heart_data (1, 2, 3, 4, 5, 6) VALUES (\'{data1}\',\'{data2}\',\'{data3}\',\'{data4}\',\'{data5}\',\'{data6}\')'
    #query = f"INSERT INTO lvad (1, 2, 3, 4, 5, 6) VALUES ("{data1}","{data2}","{data3}","{data4}","{data5}','{data6}');"
    #query = "INSERT INTO heart_data (1, 2, 3, 4, 5, 6) VALUES (%s,%s,%s,%s,%s,%s)",(data1,data2,data3,data4,data5,data6)
    print(query)
    cursor.execute(query)
    conn.commit()

    print("data has ben sent")
    print(" ")
    time.sleep(0.5)

When I run the code above, I receive "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 '1, 2, 3, 4, 5, 6) VALUES ('0.28548753906307667','2.8548753906307667','0.28280502' at line 1" error.

Yes, the error speaks for itself; however, I could not manage to find the right way to format the query. On the commented lines, I tried different ways to format the string, however, it did not work.

I checked my MySQL version and it is 5.7.33. I checked the documentation according to what the error suggests, however, I still did not manage to recover from the error.

Can you help me with that?

Here is my table format:

enter image description here

Ali Gökkaya
  • 408
  • 6
  • 20
kucar
  • 245
  • 3
  • 13
  • 1
    Why would you use numbers as column names in the first place? Surely there are more descriptive names for your columns. – Barmar Sep 07 '21 at 21:35

2 Answers2

3

You can't use numbers as columns names without backticks

query = "INSERT INTO heart_data (`1`,`2`, `3`, `4`, `5`, `6`) VALUES (%s,%s,%s,%s,%s,%s)"
cursor.execute(query,(data1,data2,data3,data4,data5,data6))
nbk
  • 45,398
  • 8
  • 30
  • 47
1

https://dev.mysql.com/doc/refman/8.0/en/identifiers.html

Identifiers may begin with a digit but unless quoted may not consist solely of digits.

So if you want your column names to be 1, 2, 3, etc, they need to be delimited with back-ticks.

It would be easier if you choose more conventional names for your columns.

Bill Karwin
  • 538,548
  • 86
  • 673
  • 828