day39-Python连接MySQL

一、视图和索引

1.视图

1.创建视图

create view vw_dept_emp_count as 
select dname as 部门名称, count(t1.dno) as 人数 
from tbemp t1 right outer join tbdept t2 on t1.dno=t2.dno
group by t1.dno
order by 人数;

2.查看视图

select * from vw_dept_emp_count;

3.删除视图

drop view vw_dept_emp_count

2.索引

1.创建索引

create index inx_emp_ename on tbemp (ename);

create index inx_emp_ename on tbemp (ename(2));

2.删除索引

alter table tbemp drop index inx_emp_ename;

注意:表的索引相当于一本书的目录 它可以加速查询,但是索引会让增删改变得更慢,因为增删改数据时,索引也需要更新,所以索引要建在经常被用作查询筛选条件的列上。


二、Python连接MySQL

1.添加记录

import pymysql


def main():
    no = int(input('部门编号:'))
    name = input('部门名称:')
    loc = input('部门所在地:')
    # 1.创建连接(主机、端口、用户名、口令、数据库名)
    # autocommit = True -> 设置自动提交
    con = pymysql.connect(host='localhost', port=3306,
                          user='root', passwd='123456',
                          database='hrs', charset='utf8',
                          autocommit=True)
    try:
        # 2.通过连接对象的cursor方法获取游标
        with con.cursor() as cursor:
            # 3.通过游标对象的execute方法向数据库服务器发出SQL
            result = cursor.execute(
                'insert into tbdept values(%s,%s,%s)', (no, name, loc))
            # 4.处理服务器返回的信息
            if result == 1:
                print('添加成功')
                # con.commit() -> 提交操作
                con.commit()
    except pymysql.MySQLError as e:
        print(e)
        con.rollback()
    finally:
        # 5.关闭连接释放资源
        con.close()


if __name__ == '__main__':
    main()

2.删除记录

import pymysql


def main():
    no = int(input('部门编号:'))
    # 1.创建连接(主机、端口、用户名、口令、数据库名)
    # autocommit = True -> 设置自动提交
    con = pymysql.connect(host='localhost', port=3306,
                          user='root', passwd='123456',
                          database='hrs', charset='utf8',
                          autocommit=True)
    try:
        # 2.通过连接对象的cursor方法获取游标
        with con.cursor() as cursor:
            # 3.通过游标对象的execute方法向数据库服务器发出SQL
            result = cursor.execute(
                'delete from tbdept where dno=%s', (no,))
            # 4.处理服务器返回的信息
            if result == 1:
                print('删除成功')
    except pymysql.MySQLError as e:
        print(e)
        con.rollback()
    finally:
        # 5.关闭连接释放资源
        con.close()


if __name__ == '__main__':
    main()

3.更新记录

import pymysql


def main():
    no = int(input('部门编号:'))
    name = input('新部门名称:')
    loc = input('新部门所在地:')
    # 1.创建连接(主机、端口、用户名、口令、数据库名)
    # autocommit = True -> 设置自动提交
    con = pymysql.connect(host='localhost', port=3306,
                          user='root', passwd='123456',
                          database='hrs', charset='utf8',
                          autocommit=True)
    try:
        # 2.通过连接对象的cursor方法获取游标
        with con.cursor() as cursor:
            # 3.通过游标对象的execute方法向数据库服务器发出SQL
            result = cursor.execute(
                'update tbdept set dname=%s, dloc=%s where dno=%s', (name, loc, no))
            # 4.处理服务器返回的信息
            if result == 1:
                print('更新成功')
    except pymysql.MySQLError as e:
        print(e)
        con.rollback()
    finally:
        # 5.关闭连接释放资源
        con.close()


if __name__ == '__main__':
    main()

4.查询记录

import pymysql


class Dept(object):

    def __init__(self, no, name, loc):
        self.no = no
        self.name = name
        self.loc = loc

    def __str__(self):
        return f'{self.no}\t{self.name}\t{self.loc}'


def main():
    con = pymysql.connect(host='localhost',
                          port=3306,
                          user='root',
                          passwd='123456',
                          database='hrs',
                          charset='utf8',
                          cursorclass=pymysql.cursors.DictCursor)
    try:
        with con.cursor() as cursor:
            cursor.execute('select dno no, dname name, dloc loc from tbdept')
            depts = cursor.fetchall()
            # 方法一:
            for dept_dict in depts:
                # **dept -> 解包
                dept = Dept(**dept_dict)
                print(dept)

            """
           方法二:
           for dept in depts:
                print(dept['no'], dept['name'], dept['loc'])
           """

            """
           方法三:
           print('编号\t名称\t所在地')
           for dept in depts:
                print(f'{dept[0]}\t\t{dept[1]}\t{dept[2]}')
                print('-' * 22)
           """
            
    except pymysql.MySQLError as e:
        print(e)
    finally:
        con.close()


if __name__ == '__main__':
    main()

5.一次性添加多条记录

import pymysql


def main():
    # 1.创建连接(主机、端口、用户名、口令、数据库名)
    # autocommit = True -> 设置自动提交
    con = pymysql.connect(host='localhost',
                          port=3306,
                          user='root',
                          passwd='123456',
                          database='hrs',
                          charset='utf8',
                          autocommit=True)
    try:
        # 2.通过连接对象的cursor方法获取游标
        with con.cursor() as cursor:
            # 3.通过游标对象的executemany方法可以一次性执行多个SQL操作
            # 相当于是以批处理的方式执行SQL(效率比一个个执行单条SQL效率更高)
            result = cursor.executemany(
                'insert into tbdept values(%s,%s,%s)',
                ((100, '研发2部', '上海'),
                 (110, '销售3部', '深圳'),
                 ('120', '运维2部', '重庆'))
            )
            print(result)
            # 4.处理服务器返回的信息
            if result == 1:
                print('添加成功')
                # con.commit() -> 提交操作
                con.commit()
    except pymysql.MySQLError as e:
        print(e)
        con.rollback()
    finally:
        # 5.关闭连接释放资源
        con.close()


if __name__ == '__main__':
    main()

你可能感兴趣的:(day39-Python连接MySQL)