MySQLdb: Operand should contain 1 column(s)

2019-07-28 15:35发布

问题:

I am trying to insert some data into a MySQL database, using Python and MySQLdb. When I execute the following function in my program, MySQL returns error "1241, 'Operand should contain 1 column(s)'"

User, password and database are correct, the table is existing and all rights are granted.

def write_to_mysql(pname, dat, like, reachs, talker, friendsfans):
''
    try:
        con = mdb.connect(user='user', passwd='password', host='localhost', db='database');
    except Exception. err:
        print(err)

    with con:

        cur = con.cursor()
        cur.execute("INSERT INTO fbinsights (page, datum, likes, reach, talking, fanfriends) VALUES( %s, %s, %s, %s, %s, %s)", (pname, dat, like, reachs, talker, friendsfans))

    connection.commit()

Where's the mistake?

Full traceback:

File "insights.py", line 111, in <module>
    main()
  File "insights.py", line 108, in main
    write_to_mysql(PAGE_NAME, date, likes_atm, reach_day, talking_day, friends_of_fans)
  File "insights.py", line 90, in write_to_mysql
    cur.execute("INSERT INTO fbinsights (page, datum, likes, reach, talking, fanfriends) VALUES( %s, %s, %s, %s, %s, %s)", (pname, dat, like, reachs, talker, friendsfans))
  File "/usr/local/lib/python2.7/site-packages/MySQL_python-1.2.3-py2.7-freebsd-9.0-RELEASE-p3-amd64.egg/MySQLdb/cursors.py", line 174, in execute
    self.errorhandler(self, exc, value)
  File "/usr/local/lib/python2.7/site-packages/MySQL_python-1.2.3-py2.7-freebsd-9.0-RELEASE-p3-amd64.egg/MySQLdb/connections.py", line 36, in defaulterrorhandler
    raise errorclass, errorvalue
_mysql_exceptions.OperationalError: (1241, 'Operand should contain 1 column(s)')

回答1:

@schlamar answered it. Wrong types passed to MySQL.



回答2:

I had this error when I was generating a SELECT query with columns to select enclosed (by mistake) in parentheses: SELECT (id, name, age) FROM members;

Note that it does not raise this error if you have just one column listed in parentheses.