mysql及python交互

  mysql在以前写过一次,那时是我刚刚进入博客,今天介绍一下mysql的python交互,固然前面会把mysql基本概述一下。python

 

  目录:
1、命令脚本(mysql)
    一、基本命令
    二、数据库操做命令
    三、表操做命令
    四、数据操做命令
    五、查
    六、关联
2、python交互
    一、数据库链接
    二、建立数据库表
    三、插入数据
    四、更新数据库
    五、删除数据
    六、数据库查询
3、mysql封装(方便使用)
    一、python封装的my_sql类
    二、案例(调用my_sql类)

 

1、命令脚本

一、基本命令

  (1)启动服务

    • 以管理员身份运行cmd
    • net start 服务名称

  (2)中止服务

    • 以管理员身份运行cmd
    • net stop 服务名称

  (3)链接数据库

    • 格式:mysql - u root - p ->输入密码

  (4)退出登陆(断开链接)

    • exit或quit

  (5)查看版本(链接后能够执行)

    • select version()

  (6)显示当前时间(链接后能够执行)

    • select now()

  (7)远程链接

    • mysql - h ip地址 - u 用户名 - p --->输入对方mysql密码

二、数据库操做命令

  (1)建立数据库

    • create database 数据库名 charset = utf8

  (2)删除数据库

    • drop database 数据库名

  (3)切换数据库

    • use 数据库名

  (4)查看当前选择的数据库

    • select database()

三、表操做命令

  (1)查看数据库中全部表

    • show tables

  (2)建立表

    • create table 表名(列及类型)

    eg:create table student(id int auto_increment primary key,
               name varchar(20) not null)
    注:auto_increment 自增加      primary key 主键     not null 非空mysql

  (3)删除表

    • drop table 表名

  (4)查看表结构

    • desc 表名

  (5)查看建表语句

    • show create table 表名

  (6)重命名表

    • rename table 原表名 to 新表名

  (7)修改表

    • alter table 表名 add | change | drop 列名

四、数据操做命令

  (1)增

    a、全列插入
      insert into 表名 values(...)
      eg:
      insert into student values(0, "tom", "北京")
      主键列是自动增加,可是在全列插入时须要占位,一般使用0,插入成功之后以实际数据为准
    b、缺省插入
      insert into 表名(列1,列2..) values(值1,值2..)
    c、同时插入多条数据
      insert into 表名 values(...), (...), ...sql

  (2)删

    delete from 表名 where 条件
    不写条件则全删数据库

  (3)改

    update 表名 set 列1 = 值1, 列2 = 值2, ... where 条件框架

  (4)查

    查询表中的所有数据
    select * from 表名函数

五、查

  (1)基本语法

    select * from 表名fetch

      • from关键字后面是表名,表示数据来源于这张表
      • select后面写表中的列名,若是是 * 表示在结果集中显示表中额全部列
      • 在select后面的列名部分,可使用as为列名起别名,这个别名显示在结果集中
      • 若是要查询多个列,之间使用逗号分隔

    # eg:select name as a,age from student;ui

  (2)消除重复行

    在select后面列前面使用distinct能够消除重复的行
    eg:select distinct gender from studentspa

  (3)条件查询

    a、语法
      select * from 表名 where 条件
    b、比较运算符
      等于(=) 大于(>) 小于(<) 大于等于(>=) 小于等于(<=) 不等于(!= 或 <>)
    c、逻辑运算符
      and or not
    d、模糊查询
      like
      % 表示任意多个任意字符
      _ 表示一个任意字符
    e、范围查询
      in 表示在一个非连续的范围内
      between。。。and。。。 表示在一个连续的范围内
      eg:where id in (8, 10, 13)
    f、空判断
      注意:null与""是不一样的
      判断空:is null
      判断非空:is not null
    g、优先级
      小括号,not,比较运算符,逻辑运算符
      and比or优先级高,同时出现并但愿先选or,须要结合括号来使用code

  (4)聚合

    为了快速获得统计数,提供了5个聚合函数
    a、count(*) 表示计算总行数,括号中能够写 * 或列名
    b、max(列) 表示求此列的最大值
    c、min(列) 表示求此列的最小值
    d、sum(列) 表示求此列的和
    e、avg(列) 表示求此列的平均值

  (5)分组

    按照字段分组,表示此字段相同的数据会被放到一个集合中。分组后,只能查询出相同的数据列,对于有差别的数据列没法显示在结果集中

    能够对分组后的数据进行统计,作聚合运算
    select 列1, 列2, 聚合... from 表名 group by 列1, 列2 having 列1, 列2
    eg:  查询男女生总数
      select gender, count(*) from student group by gender
    where与having的区别:where是对from后面指定的表进行筛选,属于对原始数据的筛选;having是对group by的结果进行筛选。

  (6)排序

    select * from 表名 order by 列1 asc | desc, 列2 asc | desc, ...
    a、将数据按照列1进行排序,若是某些列1的值相同则按照列2排序
    b、默认按照从小到大的顺序
    c、asc升序
    d、desc降序

  (7)分页

    select * from 表名 limit start, count
    从start开始,看count条

六、关联

  • 建表语句

  (1)create table class(id int auto_increment primary key, name varchar(20) not null, stuNum int not null)
  (2)create table students(id int auto_increment primary key, name varchar(20) not null, gender bit default 1, classid int not bull, foreign key(classid) references class(id))

  • 插入一些数据:

  (1)insert into class values(0, "python1", 50), (0, "python2", 60), (0, "python3", 70)

  (2)insert into students values(0, "tom", 1, 1)

  • 关联查询:

  (1)select students.name, class.name from class inner join students on class.id = students.classid

  • 分类:

  (1)表A inner join 表B
    表A与表B匹配的行会出如今结果集中
  (2)表A left join 表B
    表A与表B匹配的行会出如今结果集中,外加表A中独有的数据,未对应的数据使用null填充
  (3)表A right join 表B
    表A与表B匹配的行会出如今结果集中,外加表B中独有的数据,未对应的数据使用null填充

2、python交互

一、链接数据库

 1 import pymysql  2 
 3 
 4 # 链接数据库
 5 # 参数一:mysql服务所在主机的IP
 6 # 参数二:用户名
 7 # 参数三:密码
 8 # 参数四:要链接的数据库名
 9 db = pymysql.connect("localhost", "root", "111111", "student") 10 
11 # 建立一个cursor对象
12 cursor = db.cursor() 13 -----------------------------------------------------------------------------------------
14 # 要执行的sql语句
15 sql = "select version()"
16 
17 # 执行sql语句
18 cursor.execute(sql) 19 
20 # 获取返回的信息
21 data = cursor.fetchone() 22 print(data) 23 ----------------------------------------------------------------------------------------
24 # 断开
25 cursor.close() 26 db.close()

  这里我选择的是pymysql,其实这个和MySQLdb相差无几,命令也很像。链接时,主机IP若是是在本机,直接使用localhost便可,也能够写IP地址,这样能够实现远程的链接。虚线中间部分是要进行不一样操做时须要更改的部分。

二、建立数据库表

  上面给出了链接数据库的代码,其实后面的操做就简单多了,外部框架不变,只须要改内部的sql语句,以及个别的一些操做。

1 # 检查表是否存在,若是有则删除
2 cursor.execute("drop table if exists bancard") 3 
4 # 建表
5 sql = "create table bandcard(id int auto_increment primary key, money int not null)"
6 cursor.execute(sql)

三、插入数据

1 sql = "insert into bandcard values(0, 300)"
2 try: 3  cursor.execute(sql) 4     db.commit() # 执行这条语句才插入
5 except: 6     # 若是提交失败,回滚到上一次数据
7     db.rollback()

四、更新数据库

1 sql = "update bandcard set money=1000 where id=1"
2 try: 3  cursor.execute(sql) 4  db.commit() 5 except: 6     # 若是提交失败,回滚到上一次数据
7     db.rollback()

  能够看到,后面的操做基本上以及回归mysql自己,你们记住这样一个流程就能够了。

五、删除数据

1 sql = "delete from bandcard where money=200"
2 try:
3     cursor.execute(sql)
4     db.commit()
5 except:
6     # 若是提交失败,回滚到上一次数据
7     db.rollback()

六、数据库查询操做

  • fetchone()

    功能:获取下一个查询结果集,结果集是一个对象

  • fetchall()

    功能:接收所有的返回的行

  • rowcount

    是一个只读属性,返回execute()方法影响的行数

 1 sql = "select * from bandcard where money>200"
 2 try:  3  cursor.execute(sql)  4     # 返回查询结果
 5     reslist = cursor.fetchall()  6     for row in reslist:  7         print("%d--%d" % (row[0], row[1]))  8 except:  9     # 若是提交失败,回滚到上一次数据
10     db.rollback()

3、mysql的封装(方便之后使用时直接调用)

 1 import pymysql  2 
 3 
 4 class my_sql():  5 
 6     def __init__(self, host, user, passwd, dbName):  7         self.host = host  8         self.user = user  9         self.passwd = passwd 10         self.dbName = dbName 11 
12     def connect(self): 13         self.db = pymysql.connect( 14  self.host, self.user, self.passwd, self.dbName) 15         self.cursor = self.db.cursor() 16 
17     def close(self): 18  self.cursor.close() 19  self.db.close() 20 
21     def get_one(self, sql): 22         res = None 23         try: 24  self.connect() 25  self.cursor.execute(sql) 26             res = self.cursor.fetchone() 27  self.close() 28         except: 29             print("查询失败") 30         return res 31 
32     def get_all(self, sql): 33         res = () 34         try: 35  self.connect() 36  self.cursor.execute(sql) 37             res = self.cursor.fetchall() 38  self.close() 39         except: 40             print("查询失败") 41         return res 42 
43     def insert(self, sql): 44         return self.__edit(sql) 45 
46     def update(self, sql): 47         return self.__edit(sql) 48 
49     def delete(self, sql): 50         return self.__edit(sql) 51 
52     def __edit(self, sql): 53         count = 0 54         try: 55  self.connect() 56             count = self.cursor.execute(sql) 57  self.db.commit() 58  self.close() 59         except: 60             print("事务提交失败") 61             self.db.rollback()

  上面的类中封装了用python封装了对mysql的链接,增,删,改,查等功能,在从此使用的时候,彻底能够直接调用其中的方法,避免重复造轮子嘛。下面给一个使用的案例:

1 from my_sql import my_sql 2 
3 # 这个是链接mysql的参数,前面有解释到,使用时候链接上本身的数据库就好
4 s = my_sql("xxx.xxx.xx.x", "xxxx", "xxxxxx", "student") 5 
6 # 查询
7 res = s.get_all("select * from bandcard where money>200") 8 for row in res: 9     print("%d--%d" % (row[0], row[1]))

  固然在你使用的时候要写完整调用的类的路径,我这里是在同一个目录下写的。新建一个本身的文件,引入my_sql中的my_sql类,而后就可使用了。