简体   繁体   中英

Unable to insert values into a table using MySQL in Python

I want to update a table with some values that created in a python script in a MySQL database. Here is the line with the problem:

dbCursor.execute("INSERT INTO Solution (ProblemName, TourLength, Date, Author, Algorithm, RunningTime, Tour) VALUES ('%s', '%d', '%s', '%s', '%s', '%d', '%s')" % (sys.argv[1], bestDist, "Foo Bar", "CURDATE()", "Greedy + 2-Opt", timeAllowed, bestRoute))
dbConnection.commit()

It is generating this error:

pymysql.err.InternalError: (1136, "Column count doesn't match value count at row 1")

I've tried googling the problem and searching this website for a solution, but none of the ones that I've found exactly match mine. The fixes have also not solved my problem because of this. So I am not sure what I can do at this point. From what I can see, all of my column names match the values and the formatted variables.

What could be causing this problem?

CREATE TABLE IF NOT EXISTS Solution (
  SolutionID int(11) NOT NULL AUTO_INCREMENT,
  ProblemName varchar(32) NOT NULL,
  TourLength double NOT NULL,
  Date date DEFAULT NULL,
  Author varchar(32) DEFAULT NULL,
  Algorithm varchar(32) DEFAULT NULL,
  RunningTime int(11) DEFAULT NULL,
  Tour mediumtext NOT NULL,
  CONSTRAINT SPK PRIMARY KEY (SolutionID),
  CONSTRAINT SolPName FOREIGN KEY (ProblemName) REFERENCES Problem (Name) ON DELETE CASCADE
);

The problem is in formatting the SQL query with the % operator. In particular, you need to properly escape the parameters and also CURDATE() shouldn't be quoted.

That said, it's better to rely on the db driver to interpolate the query parameters. For that, pass them as a tuple to cursor.execute() like this:

sql = (
    "INSERT INTO Solution (ProblemName, TourLength, Date, Author, Algorithm, "
    " RunningTime, Tour) VALUES (%s, %s, CURDATE(), %s, %s, %s, %s)")
print(sql)
dbCursor.execute(sql, (sys.argv[1], bestDist, "Foo Bar", "Greedy + 2-Opt",
                       timeAllowed, bestRoute))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM