将值存储到mySQL表时出错

时间:2018-01-27 02:34:09

标签: python mysql sql mariadb

我正在尝试将数据存储到数据库中。 在我的脚本中,这对我有用,我有6个变量,包括时间戳:

mariadb_connection = mariadb.connect(user='user', password='pw', database='mydb')
cursor = mariadb_connection.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS mytable (ts TIMESTAMP, Day0 decimal (5,2), Day1 decimal (5,2), Day2 decimal (5,2), Day3 decimal (5,2), Day4 decimal (5,2), Day5 decimal (5,2))")
sql ="INSERT INTO mytable (ts, Day0, Day1, Day2, Day3, Day4, Day5)" 
sql += "VALUES (NULL, %s, %s, %s, %s, %s, %s)"
cursor.execute(sql,(day0, day1, day2, day3, day4, day5)) 
print("Storing values into SQL database")
mariadb_connection.commit()
mariadb_connection.close()

但是,如果我想存储单个值(float)(值= 7.4995244)以及时间戳,我会收到语法错误。为什么会这样?

mariadb_connection = mariadb.connect(user='user', password='pw', database='mydb')
cursor = mariadb_connection.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS mytable2 (ts TIMESTAMP, Day0 float(10,8))")
sql ="INSERT INTO mytable2 (ts, Day0)" 
sql += "VALUES (NULL, %s)"  
cursor.execute(sql,(day0)) #the error happens here
print("Storing values into SQL database")
mariadb_connection.commit()
mariadb_connection.close()

我得到的错误是:

mysql.connector.errors.ProgrammingError: 1064 (42000): 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 '%s)' at line 1

1 个答案:

答案 0 :(得分:0)

好的,问题现在解决了。正如Adam Mitchell建议的那样,我需要做以下事情:

In the cursor.execute function, try changing syntax to this: cursor.execute(sql, (Day0, ))