1. # -*- coding: utf-8 -*-
    2. import pymysql
    3. __author__ = 'dongfangyao'
    4. __date__ = '2017/12/20 下午9:17'
    5. __product__ = 'PyCharm'
    6. __filename__ = 'db1'
    7. # python操作mysql数据库的三种方式:1、pymysql 2、mysqldb 3、sqlalchemy
    8. # 1、数据库的连接
    9. conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='dongfangyao', db='dfy8899', charset='utf8')
    10. # print(conn)
    11. # 2、创建操作的游标
    12. cursor = conn.cursor()
    13. # 3、设置字符编码以及自动提交
    14. cursor.execute('set names utf8')
    15. cursor.execute('set autocommit=1')
    16. # conn.commit()
    17. # 4、编写sql语句 crud
    18. # sql = "insert into tb_user(name, pwd) values('dfy888', '222')"
    19. # sql = 'delete from tb_user where id={0}'.format(2)
    20. # sql = "update tb_user set pwd='333' where name='dfy999'"
    21. sql = 'select * from tb_user'
    22. print(sql)
    23. # 5、执行sql并且得到结果集
    24. cursor.execute(sql)
    25. # 得到结果集三种方式:fetchone() fetchemany(n) fetchall()
    26. # result = cursor.fetchall()
    27. # result = cursor.fetchone()
    28. result = cursor.fetchmany(2)
    29. print(result)
    30. # 6、关闭游标和连接
    31. cursor.close()
    32. conn.close()