search

Home  >  Q&A  >  body text

python2.7 mysql execute() problem

Part of the code to insert data:

            try:
                sql = "INSERT INTO {}({}) VALUES(%s)".format(table,cols) % q[0]
                print sql           
                result = self.cur.executemany(sql,q)
                #result = self.cur.execute(sql)
                insert_id = self.db.insert_id()
                self.db.commit()
                #判断是否执行成功
                if result:
                    return insert_id
                else:
                    return 0
            except MySQLdb.Error,e:
                #发生错误时回滚
                print "数据库错误,原因%d: %s" % (e.args[0], e.args[1])               
                self.db.rollback()

After executing the program, we get

[(u'""," http://sz.centanet.com/ershoufang/szlg13772053.html"," 345\u4e07|3\u5ba42\u5385|74.89\u5e73"," \u5357|2007\u5e74|\u4f4e\u5c42(\u517134\u5c42)|\u8c6a\u88c5|\u5eb7\u8fbe\u5c14\u82b1\u56ed\u4e94\u671f(\u8774\u8776\u5821)|"',)]
INSERT INTO zydc(follow, house_url, price_area, houseinfo) VALUES(%s)
数据库错误,原因1136: Column count doesn't match value count at row 1
None

There was no problem when I entered the insert statement manually in the database, but I don’t know why the execute error occurred.
When I insert data into a table that only stores links, there is no problem at all.
Just now when I wanted to output the cause of the error, I found that the data was inserted successfully. Then I tried to use executemany() and another error occurred.

怪我咯怪我咯2748 days ago799

reply all(1)I'll reply

  • PHPz

    PHPz2017-05-18 10:54:05

    Finally I gave up using executemany().

    INSERT INTO employees (first_name, hire_date)
    VALUES ('Jane', '2005-02-12'), ('Joe', '2006-05-23'), ('John', '2010-10-03')

    Just use the above form and execute().
    https://dev.mysql.com/doc/con...

    reply
    0
  • Cancelreply