Mac环境下MySQL的安装和基本命令的使用

mysql

  • 原文博客地址: Mac环境下MySQL的安装和基本命令的使用
  • MySQL是一种关系数据库管理系统,关系数据库将数据保存在不一样的表中,而不是将全部数据放在一个大仓库内,这样就增长了速度并提升了灵活性。
  • MySQL所使用的SQL语言是用于访问数据库的最经常使用标准化语言。
  • 因为其体积小、速度快、整体拥有成本低,尤为是开放源码这一特色,许多中小型网站为了下降网站整体拥有成本而选择了MySQL做为网站数据库。
  • MySQL是一个多用户、多线程的关系型数据库管理系统。 工做模式是基于客户机/服务器结构。目前它能够支持几乎全部的操做系统
  • 简单的来讲,MySQL是一个开放的、快速的、多线程的、多用户的SQL数据库服务器

一. MySQL的安装

工欲善其事必先利其器, 要研究MySQL咱们首先要安装MySQL, 这里只介绍Mac环境下的安装和数据库操做python

1. 下载MySQL

直接打开MySQL官网下载页, 选择mac OS系统后, 选择DMG格式下载软件mysql

SQLDownload1

接着, 会跳转到以下页面, 你只须要选择不登陆,直接下载便可(固然也能够选择注册并登陆)sql

SQLDownload2

  • 下载好后, 按照dmg里面的pkg文件一路安装便可, 可是须要注意的是
    • 除了倒数第二步以外按照默认一路安装便可
    • 倒数第二步会有一个设置管理员密码的过程, 设置好后, 必定要牢记该密码, 后期连接数据库会须要
  • 最后打开系统偏好设置, 最后会有一个MySQL的图标
  • 打开MySQL会看到默认是开启的(安装的时候按照默认设置安装的状况下)

image

到这里MySQL就已经基本安装完成了, 不须要再修改什么配置了数据库

安装Navicat for MySQL

  • Navicat for MySQL是一套专为MySQL设计的高性能数据库管理及开发工具
  • 它能够用于任何版本3.21或以上的 MySQL数据库服务器
  • 支持大部份MySQL最新版本的功能,包括触发器、存储过程、函数、事件、视图、管理用户等
  • 正版下载地址, 不过正版只有14天的试用时间
  • 安装后, 按照下图完善配置便可, 其中链接名随意, 密码即为安装MySQL环境的时候设置的密码

MySQLConten

二. MySQL的基本命令

1. 基本命令

  • 首先要打开终端(Windows中是cmd), 如下命令均是在终端运行
  • 启动/中止服务只有在Windows系统中才须要运行, Mac环境下不须要

1-1. 启动/中止服务

// 启动服务
    格式:net start 服务名称
    示例:net start titansql

// 中止服务
    格式:net stop 服务名称
    示例:net stop titansql
复制代码

1-2. 链接数据

格式:mysql -u 用户名 -p
示例:mysql -u root -p
// 此处会提示你输入密码(安装时设置的)
复制代码

1-3. 远程链接

  • 连接他人或其余服务器的数据库
    • 格式:mysql -h ip地址 -u 用户名 -p
    • 输入对方mysql密码
1-4. 其余命令

须要注意的是: 如下全部命令中如过结尾有分号(;)的必定不能省略, 不然不是一条完整的命令, 系统会提示你继续输入命令python3.x

// 查看版本(链接后能够执行)
select version();

//显示当前时间(链接后能够执行)
select now();

//退出登陆(断开链接)
quit或exit
复制代码

image

2. 数据库操做

// 一、建立数据库
    格式:create database 数据库名 charset=utf8;
    示例:create database titansql charset=utf8;
// 二、删除数据库
    格式:drop database 数据库名;
    示例:drop database titansql;
// 三、切换数据库
    格式:use 数据库名;
    示例:use titansql;
// 四、查看当前选择的数据库
    select database();
    
复制代码

建立完成记得刷新Navicat for MySQLbash

image

3. 表操做

// 一、查看当前数据库中全部表
    show tables;
    
// 二、建立表
    格式:create table 表名(列及类型);
    说明:
        //id, name, age: 等为字段名
        //auto_increment: 表示自增加 
        //primary key: 表示主键 
        //int, varchar(20): 等为数据类型, 20为可存储的字节数
        //not null: 表示不为空
        //default: 为设置默认值
    示例:create table student(id int auto_increment primary key, name varchar(20) not null, age int not null, gender bit default 1, address varchar(20), isDelete bit default 0);
    
    
// 三、删除表
    格式:drop table 表名;
    示例:drop table student;
    
// 四、查看表结构
    格式:desc 表名;
    示例:desc student;
    
// 五、查看建表语句
    格式:show create table 表名;
    示例:show create table student;
    
// 六、重命名表名
    格式:rename table 原表名 to 新表名;
    示例:rename table car to newCar;
    
// 七、修改表
    格式:alter table 表名 add|change|drop 列名 类型;
    示例:alter table newcar add isDelete bit default 0
复制代码

4. 数据操做

1、增
    a、全列插入
        格式:insert into 表名 values(...);
        说明:主键列是自动增加,可是在全列插入时须要占位,一般使用0,插入成功之后以实际数据为准
        示例:insert into student values(0, "tom", 19, 1, "北京", 0);
    b、缺省插入
        格式:insert into 表名(列1,列2,……) values(值1,值2,……);
        示例:insert into student(name, age, address) values("titan", 19, "上海");
    c、同时插入多条数据
        格式:insert into 表名 values(...),(...),……
        示例:insert into student values(0, "jun", 18, 0, "北京", 0), (0, "poi", 22, 1, "海南", 0), (0, "coder", 20, 0, "石家庄", 0);
2、删
    格式:delete from 表名 where 条件;  
    示例:delete from student where id=4;
    注意:没有条件是所有删除,慎用
3、改
    格式:update 表名 set 列1=值1,列2=值2,…… where 条件;
    示例:update student set age=16 where id=7;  
    注意:没有条件是所有列都修改,慎用
4、查
    说明:查询表中的所有数据
    格式:select * from 表名;
    示例:select * from student;

复制代码

5. 查询数据

一、基本语法

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

//查询某列数据
select name, age from student;

//以别名显示搜索结果
select name as a, age from student;
复制代码

别名

消除重复行

  • select后面列前面使用distinct能够消除重复的行
  • 示例:
select gender from student;
select distinct gender from student;
复制代码

distinct

条件查询

// 一、语法
    select * from 表名 where 条件
    
// 二、比较运算符
        等于        =
        大于        >
        小于        <
        大于等于    >=
        小于等于    <=
        不等于      !=或<>
    需求:查询id值大于8的全部数据
    示例:select * from student where id>8;
        
// 三、逻辑运算符
        and    而且
        or     或者
        not    非
            
    需求:查询id值大于7的女同窗
    示例:select * from student where id>7 and gender=0;
    
// 四、模糊查询(like)
        %: 表示任意多个任意字符
        _: 表示一个任意字符

    需求:查询姓习的同窗
    示例:
        select * from student where name like "习%";
        select * from student where name like "习_";
        
// 五、范围查询
        in                表示在一个非连续的范围内
        between...and...  表示在一个连续的范围内

    需求:查询编号为81012的学生
    示例:select * from student where id in (8,10,12);
    需求:查询编号为68的学生
    示例:select * from student where id between 6 and 8;

// 六、空判断
        注意:null与""是不一样的
        判断空:is null
        判断非空: is not null

    需求:查询没有地址的同窗
    示例:select * from student where address is null;
    需求:查询有地址的同窗
    示例:select * from student where address is not null;

// 七、优先级
        小括号,not 比较运算符,逻辑运算符
        and比or优先级高,若是同时出现并但愿先选or,须要结合()来使用
复制代码

聚合操做

  • 为了快速等到统计数据,提供了5个聚合函数
    • count(*): 表示计算总行数,括号中能够写*和列名
    • max(列): 表示求此列的最大值
    • min(列): 表示求此列的最小值
    • sum(列): 表示求此列的和
    • avg(列): 表示求此列的平均值
//需求:查询学生总数
select count(*) from student;

//需求:查询女生的编号最大值
select max(id) from student where gender=0;

//需求:查询女生的编号最小值
select min(id) from student where gender=0;
        
//需求:查询全部学生的年龄和
select sum(age) from student;

//需求:查询全部学生的年龄平均值
select avg(age) from student;
复制代码

分组

  • 按照字段分组,表示此字段相同的数据会被放到一个集合中。
  • 分组后,只能查询出相同的数据列,对于有差别的数据列没法显示在结果集中
  • 能够对分组后的数据进行统计,作聚合运算
  • 语法:
    • select 列1,列2,聚合…… from 表名 group by 列1,列2,列3,……;
  • 需求:查询男女生总数
  • 示例:
select gender,count(*) from student group by gender;
select name,gender,count(*) from student group by gender,age;
复制代码

分组后的数据筛选:服务器

select 列1,列2,聚合…… from 表名 group by 列1,列2,列3,…… having 列1,……聚合……;

示例:select gender,count(*) from student group by gender having gender;
复制代码

wherehaving的区别:多线程

  • where是对from后面指定的表进行筛选,属于对原始数据的筛选
  • having是对group by的结果进行筛选

排序

  • 语法:select * from 表名 order by 列1 asc|desc,列2 asc|desc , ……;
  • 说明:
    • 将数据按照列1进行排序,若是某些列1的值相同,则按照列2进行排序
    • 默认按照从小到大的顺序排序
    • asc: 升序
    • desc: 降序
//需求:将没有被删除的数据按年龄排序
select * from student where isDelete=0 order by age desc;
select * from student where isDelete=0 order by age desc, id desc;
复制代码

分页

  • 语法:select * from 表名 limit start,count;
  • 说明:start索引从0开始
  • 示例:
select * from student limit 0,3;
select * from student limit 3,3;
select * from student where gender=1 limit 0,3;
复制代码

关联

// 建表语句:
    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 null, foreign key(classid) references class(id));


// 查询全部数据
    select * from students;
    

    /* 关联查询: 分类: 一、表A inner join 表B: 表A与表B匹配的行会出如今结果集中 二、表A left join 表B: 表A与表B匹配的行会出如今结果集中,外加表A中独有的数据,未对应的数据使用null填充 三、表A right join 表B: 表A与表B匹配的行会出如今结果集中,外加表B中独有的数据,未对应的数据使用null填充 */
select students.name,class.name from class inner join students on class.id=students.classid;

select students.name,class.name from class left join students on class.id=students.classid;

select students.name,class.name from class right join students on class.id=students.classid;

复制代码

至此, MySQL中一些经常使用的命令行也基本介绍完了, 下面看一些MySQLPython是如何进行交互的函数

MySQLPython的交互

  • Python要对MySQL数据库进行操做, 须要引入pymysql模块
  • pymsqlPython中操做MySQL的模块, 而且pymysql支持python3.x版本
  • 首先要先安装pymysql, 终端执行一下语句
pip3 install pymysql
复制代码

1. 建立数据库链接

# 连接数据库
# 参数1:mysql服务所在主机的IP(能够是IP地址, 本机连接能够是localhost)
# 参数2:用户名
# 参数3:密码
# 参数4:要链接的数据库名

db = pymysql.connect('localhost', 'root', 'titanjun', 'titansql')


# 建立游标, 查询数据默认为元组类型
cursor = db.cursor()

# 建立sql语句
sql = "select version()"

# 执行sql语句
cursor.execute(sql)

# 获取返回的信息
data = cursor.fetchone()
print(data)

# 关闭游标
cursor.close()

# 关闭数据库
db.close()

复制代码

2. 建立表

import pymysql

db = pymysql.connect('localhost', 'root', 'jun.0929', 'titansql')

# 建立游标, 查询数据默认为元组类型
cursor = db.cursor()

# 建表
# 在建表以前要检查表是否存在, 若是存在则删除
cursor.execute("drop table if exists userinfo")

# 建立表
try:
    sql = "create table userinfo(id int auto_increment primary key, age int not null)"
    cursor.execute(sql)
    print('建立成功')
except:
    print('建立表失败')


cursor.close()
db.close()
复制代码

3. 在表中插入数据

import pymysql

db = pymysql.connect('localhost', 'root', 'jun.0929', 'titansql')

cursor = db.cursor()

# 插入数据的字符串命令
sql = 'insert into userinfo values'

for i in range(10, 20):
    ageStr = "(0, %d)" % i
    addsql = sql + ageStr

    try:
        cursor.execute(addsql)
        # 提交到数据库, 否则没法保存新建或者修改的数据
        db.commit()
        print('插入数据成功')
    except:
        # 若是提交失败则回滚到上一次的提交, 不然下一次提交可能会冲突
        db.rollback()
        print('插入数据失败')

cursor.close()
db.close()
复制代码

4. 修改/更新/删除数据

import pymysql

db = pymysql.connect('localhost', 'root', 'jun.0929', 'titansql')
cursor = db.cursor()

# 修改/更新数据命令字符串
sql = 'update userinfo set age=30 where id=4'
# 删除数据命令字符串
# sql = 'delete from userinfo where age=16'

try:
    cursor.execute(sql)
    db.commit()
    print('数据更新成功')
except:
    db.rollback()
    print('数据更新失败')

cursor.close()
db.close()
复制代码

5. 查询数据

  • fetchone: 获取下一个查询结果集,结果集是一个对象
  • fetchall: 接收所有的返回的行
  • rowcount: 是一个只读属性,返回execute()方法影响的行数
import pymysql

db = pymysql.connect('localhost', 'root', 'jun.0929', 'titansql')
cursor = db.cursor()

# 查询数据字符串
sql = 'select * from userinfo where age>16'

try:
    cursor.execute(sql)

    # 得到一条查询数据
    print(cursor.fetchone())
    print('查询到-%d-条数据' % cursor.rowcount)

    result = cursor.fetchall()
    for row in result:
        print('%d--%d' % (row[0], row[1]))

    print('数据查询成功')

except:
    print('数据查询失败')

cursor.close()
db.close()
复制代码

至此, Python和MySQL交互的最基本最简单的使用也介绍完了, 若有不足之处还望告知工具

相关文章
相关标签/搜索