python3操作mysql数据库增删改查


  1. #!/usr/bin/python3
  2. import pymysql
  3. import types
  4. db=pymysql.connect("localhost","root","123456","python");
  5. cursor=db.cursor()
  6. #创建user表
  7. cursor.execute("drop table if exists user")
  8. sql="""CREATE TABLE IF NOT EXISTS `user` (
  9. `id` int(11) NOT NULL AUTO_INCREMENT,
  10. `name` varchar(255) NOT NULL,
  11. `age` int(11) NOT NULL,
  12. PRIMARY KEY (`id`)
  13. ) ENGINE=InnoDBDEFAULT CHARSET=utf8 AUTO_INCREMENT=0"""
  14. cursor.execute(sql)
  15. #user插入数据
  16. sql="""INSERT INTO `user` (`name`, `age`) VALUES
  17. ('test1', 1),
  18. ('test2', 2),
  19. ('test3', 3),
  20. ('test4', 4),
  21. ('test5', 5),
  22. ('test6', 6); """
  23. try:
  24. # 执行sql语句
  25. cursor.execute(sql)
  26. # 提交到数据库执行
  27. db.commit()
  28. except:
  29. # 如果发生错误则回滚
  30. db.rollback()
  31. #更新
  32. id=1
  33. sql="update user set age=100 where id='%s'" % (id)
  34. try:
  35. cursor.execute(sql)
  36. db.commit()
  37. except:
  38. db.rollback()
  39. #删除
  40. id=2
  41. sql="delete from user where id='%s'" % (id)
  42. try:
  43. cursor.execute(sql)
  44. db.commit()
  45. except:
  46. db.rollback()
  47. #查询
  48. cursor.execute("select * from user")
  49. results=cursor.fetchall()
  50. for row in results:
  51. name=row[0]
  52. age=row[1]
  53. #print(type(row[1])) #打印变量类型
  54. print ("name=%s,age=%s" % \
  55. (age, name))

【python3操作mysql数据库增删改查】转载于:https://www.cnblogs.com/meng-wei-zhi/p/8214750.html

    推荐阅读