Python操作Mysql数据库(pymysql库)

我就是我 2023-01-01 03:59 288阅读 0赞

创建数据表

  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. # 建立数据库连接
  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. # cursor默认是不会提交的,因为这是插入语句,所以必须提交保存
  15. # 提交插入的sql语句
  16. connection.commit()
  17. with connection.cursor() as cursor:
  18. # 读取一条记录
  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()

发表评论

表情:
评论列表 (有 0 条评论,288人围观)

还没有评论,来说两句吧...

相关阅读