Use of execute and executemany for Python mysqldb

Source: Internet
Author: User

If you are using Executemany to BULK insert data, be aware of the following:

conn = MySQLdb.connect (host = "localhost", user = "Root", passwd = "password", db = "MyDB", charset= ' utf8′)
cursor = Conn.cursor ()
sql = "INSERT into myTable (Created_day,name,count) VALUES (%s,%s,%s) on DUPLICATE KEY UPDATE count=count+values (count)"
args=[("2012-08-27", "name1", [+]), ("2012-08-27", "Name1", "$"), ("2012-08-27", "name2", 300)]
Try
Cursor.executemany (SQL, args)
Except Exception as E:
PRINT0 ("Error executing mysql:%s:%s"% (SQL, E))
Finally
Cursor.close ()
Conn.commit ()
Conn.close ()

Here, args is an array containing multiple tuples, each of which corresponds to one of the data in MySQL, noting that the created_day corresponding to%s in this case has no quotation marks. It is speculated that Executemany himself first makes a regular match to the SQL statement%s then, on this basis, the string is embedded, if the%s is enclosed in quotation marks, insert MySQL will appear "0000-00-00″ type of error date."

If a one-time to insert a lot of data, it is strongly recommended to use Executemany, from their own experience, a single insert requires 2-3 hours of data insertion, using Executemany only 2-3 seconds!!!

Here Executemany and on DUPLICATE KEY update are used when combined with SQL general mode, i.e.: sql= "INSERT into myTable (created_day,name,count) VALUES (% s,%s,%s) on DUPLICATE KEY UPDATE count=count+%s "will be reported bug:not all arguments converted during string formatting.

Use of execute and executemany for Python mysqldb

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.