插入多行

  1. import mysql.connector
  2.  
  3. mydb = mysql.connector.connect(
  4. host="localhost",
  5. user="myusername",
  6. passwd="mypassword",
  7. database="mydatabase"
  8. )
  9.  
  10. mycursor = mydb.cursor()
  11.  
  12. sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
  13. val = [
  14. ('Peter', 'Lowstreet 4'),
  15. ('Amy', 'Apple st 652'),
  16. ('Hannah', 'Mountain 21'),
  17. ('Michael', 'Valley 345'),
  18. ('Sandy', 'Ocean blvd 2'),
  19. ('Betty', 'Green Grass 1'),
  20. ('Richard', 'Sky st 331'),
  21. ('Susan', 'One way 98'),
  22. ('Vicky', 'Yellow Garden 2'),
  23. ('Ben', 'Park Lane 38'),
  24. ('William', 'Central st 954'),
  25. ('Chuck', 'Main Road 989'),
  26. ('Viola', 'Sideway 1633')
  27. ]
  28.  
  29. mycursor.executemany(sql, val)
  30.  
  31. mydb.commit()
  32.  
  33. print(mycursor.rowcount, "record was inserted.")