import pymysql


class Mysql(object):
    def __init__(self):
        try:
            self.conn = pymysql.connect(
                host='127.0.0.1',  # 本机地址
                port=3306,  # 端口号
                user='root',  # 用户名
                password='1234',  # 密码
                db='1909A'  # 所使用的库

            )
        except Exception as e:  # 捕获异常
            print(e)  # 输出异常
        else:
            print('连接成功')
            # cursor = conn.cursor() # 如此设置,后面的结果集是以元组的形式出现。
            # cursor = conn.cursor(pymysql.cursors.DictCursor) # 这种形式的游标,结果是以字典的形式出现。
            self.cur = self.conn.cursor()  # 获取游标

    def add(self):
        try:
            sql = 'create table bbb1(id int primary key auto_increment,name varchar (20),age int )'
            self.cur.execute(sql)  # 执行sql语句
        except Exception as e:
            print(e)
            print('创建失败')
        else:
            print('创建成功')

    def zeng(self):
        sql = "insert into bbb1 values (0,'王成阳',28),(0,'李国军',21)"
        res = self.cur.execute(sql)
        if res:
            self.conn.commit()
            print('插入成功')
        else:
            self.conn.rollback()
            print('插入失败')

    def shan(self):
        sql = "delete from bbb1 where id=2"
        res = self.cur.execute(sql)
        if res:
            self.conn.commit()
            print('删除成功')
        else:
            self.conn.rollback()
            print('删除失败')

    def update(self):
        sql = "update bbb1 set name = '李国军' where id=1"
        res = self.cur.execute(sql)
        if res:
            self.conn.commit()
            print('修改成功')
        else:
            self.conn.rollback()
            print('修改失败')

    def cha(self):
        sql = 'select * from bbb1'
        self.cur.execute(sql)
        # res = self.cur.fetchone()  # fetchone 获取一条数据 以元组的形式显示出来
        # print(res)
        res = self.cur.fetchall()  # fetchone 获取所有数据 以元组的形式显示出来
        for i in res:
            print(i)

    def close(self):
        self.cur.close()
        self.conn.close()


mysql = Mysql()
# mysql.add()
# mysql.zeng()
# mysql.shan()
# mysql.update()
mysql.cha()
# mysql.close()
'''
connect 里面的方法
1、close()
2、commit    对数据的增删改的时候用
3、rollback

cursor.execute  执行sql语句 
cursor 里面的方法
execute  执行sql 语句
close  关闭
fetchone   fetchone 获取一条数据 以元组的形式显示出来
fetchall   fetchone 获取所有数据 以元组的形式显示出来  需要循环显示
'''