python操作Mysql、视图

1、安装程式包

python3:pip install pymysql
python2:pip install MySQLdb

2、python抓取数据

 from pymysql import connect
 conn=connect(
    host='localhost',
     port=3306,
     database='python',
     user='root',
     password='root',
     charset='utf8'
 )
 cs=conn.cursor() # 光标
 cs.execute('select name from student')
 result=cs.fetchall()
 for i in result:
      print(i[0])
 cs.close()
 conn.close()
显示:
张三
张wu
张8
李四
张三
我
## 3、对象方法

commit()提交
列子:写入数据库

from pymysql import connect
conn=connect(
    host='localhost',
    port=3306,
    database='python',
    user='root',
    password='root',
    charset='utf8'
)
cs=conn.cursor()
cs.execute("insert into classes values(4,'四班')")
conn.commit()  #提交事务:将缓存 中的数据变更维护到物理表中
cs.close()
conn.close()

rollback回滚:放弃缓存中变更的数据
修改数据的命令会自动的触发事务,包括insert、update、delete

3、创建视图

创建视图的语句
create view s_c as (select student.id,student.name,student.age,student.hight,student.gender,student.birthday,classes.name as cname from student inner join classes on student.cls_id=classes.id);
查询结果:
select * from s_c
+----+--------+------+--------+--------+------------+--------+
| id | name   | age  | hight  | gender | birthday   | cname  |
+----+--------+------+--------+--------+------------+--------+
|  1 | 张三   |   18 | 175.00 | 女     | 1992-01-01 | 一班   |
|  2 | 张wu   |   19 | 171.00 | 女     | 1993-01-01 | 一班   |
|  3 | 张8    |   17 | 171.00 | 女     | 1993-01-01 | 一班   |
|  4 | 李四   |   28 | 188.00 | 男     | 1986-05-08 | 三班   |
|  5 | 张三   |   18 | 175.00 | 女     | 1992-01-01 | 一班   |
| 10 | 我     |   18 |   NULL | 隐藏   | 1991-04-19 | 二班   |
| 13 | test1  |   18 |   NULL | 隐藏   | 1991-04-19 | 二班   |
+----+--------+------+--------+--------+------------+--------+

视图一般用作多表关联查询

视图的作用:

1、提高了重用性,就像一个函数
2、对数据库重构,却不影响程序的运行
3、提高了安全性能,可以对不同的用户
4、让数据更加清晰

猜你喜欢

转载自blog.csdn.net/qq_37697566/article/details/103457087