Examples

CRUD

The following examples make use of a simple table

  1. CREATE TABLE `users` (
  2. `id` int(11) NOT NULL AUTO_INCREMENT,
  3. `email` varchar(255) COLLATE utf8_bin NOT NULL,
  4. `password` varchar(255) COLLATE utf8_bin NOT NULL,
  5. PRIMARY KEY (`id`)
  6. ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin
  7. AUTO_INCREMENT=1 ;
  1. import pymysql.cursors
  2. # Connect to the database
  3. connection = pymysql.connect(host='localhost',
  4. user='user',
  5. password='passwd',
  6. db='db',
  7. charset='utf8mb4',
  8. cursorclass=pymysql.cursors.DictCursor)
  9. try:
  10. with connection.cursor() as cursor:
  11. # Create a new record
  12. sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
  13. cursor.execute(sql, ('webmaster@python.org', 'very-secret'))
  14. # connection is not autocommit by default. So you must commit to save
  15. # your changes.
  16. connection.commit()
  17. with connection.cursor() as cursor:
  18. # Read a single record
  19. sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
  20. cursor.execute(sql, ('webmaster@python.org',))
  21. result = cursor.fetchone()
  22. print(result)
  23. finally:
  24. connection.close()

This example will print:

  1. {'password': 'very-secret', 'id': 1}