1.导包
    2.建立数据库链接
    3.查询数据
    4.关闭链接

    1. # !/usr/bin/env python
    2. # _*_ coding:utf-8 _*_
    3. # 1.导包
    4. import pymysql
    5. try:
    6. # 2.连接mysql数据库的服务
    7. connc = pymysql.Connect(
    8. # mysql服务端的IP 默认127.0.0.1/localhost-真实IP
    9. host='192.168.9.223',
    10. user='root',
    11. password="ablejava",
    12. database='db_ai_course',
    13. port=3306,
    14. charset='utf8'
    15. )
    16. # 3.创建游标对象
    17. cur = connc.cursor()
    18. # 4.编写SQL语句
    19. # 编写增加
    20. # 增加数据
    21. sql ="""
    22. INSERT INTO `tbl_demo` (`name`, `age`) VALUES (%s, %s);
    23. """
    24. add_data = ['刘德华',11]
    25. # 5.使用游标对象执行SQL
    26. cur.execute(sql, add_data)
    27. sql = 'select * from tbl_demo;'
    28. # 5.使用游标对象去调用SQL
    29. cur.execute(sql)
    30. # 6.获取查询的结果 --print()
    31. result = cur.fetchall()
    32. if result:
    33. for item in result:
    34. print(item)
    35. # 7.关闭游标对象
    36. cur.close()
    37. # 8.关闭连接
    38. connc.close()
    39. except Exception as e:
    40. print(e)