MySql基础学习笔记

249 阅读10分钟

第一章:数据库的概述

1.1作用:

image-20210730120115814

1.2常见的产品

image-20210730120431056

1.3数据库的相关概念

  • DB:

    image-20210730120634269

  • DBMS:

    image-20210730120710166

  • SQL:

    image-20210730120744705

  • 三者之间的关系:

    image-20210730120935829

1.4 数据存储的特点

image-20210730121402365

1.5mysql数据库常用的一些基本命令

安装

yum - y install mysql-servse

启动mysql服务

service mysqld start
运行端口为3306

登陆

mysql -uroot

**语法 :**mysql -uroot -proot

库和表层次关系库-->表
创建一个库create database 库名
查看有哪些库show database
进入这个库use 库名
查看表show tables

####创建表

CREATE TABLE fruits(
	f_id CHAR(10) PRIMARY KEY,
	s_id INT NOT NULL,
	f_name char(255) NOT NULL,
	f_price DECIMAL(8,2) NOT NULL,
);

语法:

CREATE TABLE 表名( 列名 类型,约束条件, ); 后面要用,隔开

####添加数据

INSERT INTO fruits(f_id,s_id,f_name,f_price) VALUES('a1',101,'apple',5.2);
INSERT INTO fruits(f_id,s_id,f_name,f_price)VALUES('b1',101,'blackberry',10.2);
INSERT INTO fruits(f_id,s_id,f_name,f_price) VALUES('bs1',102,'orange',11.2);

格式: INSERT INTO 表名(列1,列2,列3) VALUES(值1,值2,值3); 如果值的类型是字符型需要加引号。

####更新表

uodate fruits set f_name='sss' where s_id=‘101’ ;

####删除表

delete  from  fruits where  s_id=‘102’; 

####查询(以刚才创建的表为例)

  • 查询所有字段:select * from fruits
  • 查询制定字段:select * from fruits where f_name='apple'
  • 带IN关键字查询:IN(aa,bb)满足条件范围内的一个值即可匹配。 select * from fruits where f_name IN ('apple‘,’orange‘)
  • between and 范围查询用法:select * from fruits where f_price between 5 and 15; 查询价格在5到15之间的全部信息
  • 空值查询

SELECT * FROM 表名 WHERE 字段名 IS NULL; //查询字段名是NULL的记录 SELECT * FROM 表名 WHERE 字段名 IS NOT NULL; //查询字段名不是NULL的记录

  • 带AND的多条件查询

selcet * from fruits where s_id=101 and f_price>5;

  • 带or的多条件查询

selcet * from fruits where s_id=101 or f_price>5;

  • 关键字DISTINCT(查询结果不重复)

select distinct s_id from fruits;

  • 对查询结果排序(order by)

select distinct s_id from fruits order by s_id; 通过s_id进行排序,默认升序 select distinct s_id from fruits order by s_id desc; 降序排列

  • 分组查询(group by)

s_id,count(f_name),group_concat(f_name) from fruits group by s_id; 对分组过后的结果可以进行having过滤 select s_id,count(f_name),group_concat(f_name) from fruits group by s_id having count(f_name) > 1

  • limit限制查询结果的数量

select * from fruits limit 4;

  • 集合函数查询

select conut(*) from fruits; select SUM(f_price)from fruits; select AVG(f_price)from fruits; select MAX(f_price)from fruits; select MIN(f_price)from fruits;

  • 多表查询

select s.s_id,s.s_name,f.f_name,f.f_id from 表一 as s ,表二 as f where f.s_id = s.s_id //fruits 和suppliers为表名

表一用s表示,表二用f表示

  • 内连查询inner join表名 on 连接条件

select s.s_id,s.s_name,f.f_name,f.f_id from 表一 as s INER JOIN表二 as f ON f.s_id = s.s_id

1.6SQL语句

分类:

image-20210730164059205

第二章:图形化数据库客户端的使用和数据库的查询操作

2.1表的结构和介绍

  • 员工

image-20210731145810427

  • 部门

    image-20210731145947848

  • 位置

    image-20210731150048508

  • 工种编号

    image-20210731150127918

2.2——基础查询语句 select * from *

  • 语法:

image-20210731150652636

  • 查询列表(1):

image-20210731151609777

  • 查询列表(2):

    • 六,查询函数:

       select database();  #获取操作的表的名
       selsect version(); # 版本号
       selsect user(); #获取用户名
      
    • 七,起别名:

      • 使用as关键字:

        image-20210731153240628
      • 使用空格:

        image-20210731153308284
    • 八,拼接语句使用“concat”和“+”:

      image-20210731153434224
    • 九,distinct的使用(去重复):

      image-20210731153555590
    • 十,查看表的结构:

      image-20210731153725833
    • 十一,ifnull函数:

      image-20210731154357010

  • MySQL中“+”的使用:

    image-20210731152223589

2.3——条件查询 where

  • 语句结构:

image-20210731160019088

  • 特点:

    image-20210731161801011

  • like用法:

    image-20210731162928009

    image-20210731162954506

  • in关键字:

    • 功能

      image-20210731163231426

    • 案例

      image-20210731163345525

image-20210731163416752

  • between and 关键字:

    • 功能:

      image-20210731163536034

    • 案例

      image-20210731163611549

      image-20210731163718514

  • ** is null 关键字:**

    • 案例

    image-20210731163829014

    • 三种等于

      image-20210731164104461

2.4——排序查询 order by

  • 语法和举例:

    image-20210731165324401

  • 特点:

    image-20210731165409933

  • 举例:

    image-20210731165932057

    image-20210731171422872

    image-20210731171343320

2.4——常见函数

简单介绍

image-20210801154354760

1.字符函数

  • 总结:

image-20210801154551647

image-20210801154657774

2.数学函数

image-20210801163749320

image-20210801164448596

3.日期函数

image-20210801164927833

image-20210801165013704

image-20210801165036013

指定格式:!!!!!!

image-20210801164835188

4.流程控制函数

image-20210801172339412

  • **备注:**这个“ELSE”就是否则的意思,上述值都没有才实现。

image-20210801172414571

5.分组函数

image-20210801173605507

案例:

image-20210801174350897

count的补充说明:

image-20210801175152910

2.5——分组查询 GROUP BY

image-20210801175318406

语句:

image-20210801184119215

注意:

要实现不分组的筛选是用:where;

但是使用了分组,由于程序运行的顺序问题,需要新引入一个:having来实现分组后的筛选。

同时,两者所放在GROUP BY的前后位置也不同。

image-20210801182635593

案例分析:

image-20210801183902612

2.6——内连接查询 join ... on 条件

1.等值连接

  • 格式:

image-20210802161925060

  • 案例:

image-20210802154903428

image-20210802155518163

image-20210802160051678

2.非等值连接

image-20210802160942961

3.自连接

注释:

在自己的表里面,查找两次,这两次依据不一样,结果不一样,但是有联系,用到where。

image-20210802161552993

2.7——外连接查询 left/right outer join ... on

左/右外连接

注释:

就是谁多谁少的问题,主表信息对从表信息就是一对多。。。

image-20210802164324195

是SQL99语法。

image-20210802164701360

2.8——子查询

1.单行子查询

  • 概念和分类:

image-20210802172237442

  • 案例:

    image-20210802172753004

2.多行子查询

image-20210802173829312

image-20210802174703336

####3.补充exists

image-20210802175516576

2.8——分页查询 limit (起,条数)

**注释:**用于前台页面的分页显示

image-20210802180432940

案例实现:

image-20210802180525922

image-20210802181401796

image-20210802181414668

2.9——联合查询 union

说明:

image-20210802182047271

————————————————————————————————————————————————————————————

image-20210802181704818

————————————————————————————————————————————————————————————

image-20210802181953911

第三章:操作数据库

3.1 库的管理 create , drop

image-20210803163529956

注释:

其中,语句一在运行一次后的情况下,也就是说已经创建了名为“stuDB”的库时,再次运行就会报错,如果是使用java编译器,在多次运行的情况下,要避免报错,就要用到第二个语句,提前进行判断:“if not exists xxx。

3.2表的管理 create , drop

####1.创建

image-20210803165445638

附录:查看表的结构

image-20210803170133454

####2. 常见的数据类型

image-20210803170214730

image-20210803171813162

3.常见的约束

**说明:**用于去限制表中字段数据的,进一步保证数据的一致性,准确性,可靠性。

说明代码
非空not null
默认default
主键primary key
唯一unique
检查(限制条件)check
外键foreign key

image-20210803174704392

  • 代码实现:

外键的实现: 需要"constraint" 的连接,后面为主键名称,可不写(默认),然后foreign key 跟上(外键表) ,跟上“references” ,跟上列

image-20210803175836184

4.修改表

image-20210803180428793

image-20210803180621865

5.删除表和复制

image-20210803181041658

案例:

image-20210803181556120

第四章:数据的增删改

4.1插入数据

image-20210804174206564

案例:

image-20210804173636669

————————————————————————————————————————————————————————————

image-20210804173942055

4.2插入数据时主键的自增长

——————————————————————————————————————————————————————————

image-20210804174719663

4.3数据修改

image-20210804175059050

image-20210804175141231

4.4数据删除

image-20210804175204177

————————————————————————————————————————————————

比较:

image-20210804175625611

4.5事务

概念

image-20210804180137455

特性

image-20210804180312900

分类

image-20210804181130511

步骤

image-20210804181207783

第五章:JDBC的使用

5.1驱动的注册

使用反射的方式

类加载的机制:

image-20210806171132458

public class Test {
    public static void main(String[] args) throws ClassNotFoundException {
        Class.forName("com.mysql.jdbc.Driver");
    }
}

5.2获取连接

  1. 在src里写一个配置文件用来保存配置信息

    user=root
    password=root
    url=jdbc:mysql://localhost:3306/girls
    driver=com.mysql.jdbc.Driver
    
  2. Properties info = new Properties();
    info.load(new FileInputStream("src\\jdbc.properties"));
    String user = info.getProperty("user");
    String password = info.getProperty("password");
    String driver = info.getProperty("driver");
    String url = info.getProperty("url");
    
  3. Connection connection = DriverManager.getConnection(url,user,password);
    
    System.out.println("连接成功");
    

5.3执行增删改查

image-20210806174744602

//3.增删改查
String sql = "select id,name,sex,borndate from beauty";
//获取执行sql命令的对象
Statement statement = connection.createStatement();
//执行sql语句
ResultSet set = statement.executeQuery(sql);//执行查询语句,返回一个结果集
//显示查询结果
boolean flag = set.next();
int id = set.getInt(1);
String name = set.getString(2);
String sex = set.getString(3);
Date data = set.getDate(4);
System.out.println(id+"\t"+name+"\t"+sex+"\t"+data+"\t");


//4.关闭连接
set.close();
statement.close();
connection.close();

结果:

image-20210806180002910

循环:

while(set.next()){
int id = set.getInt(1);
String name = set.getString(2);
String sex = set.getString(3);
Date data = set.getDate(4);
System.out.println(id+"\t"+name+"\t"+sex+"\t"+data+"\t");}

结果:

image-20210806180223695

5.4总结

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;


public class Test {
    public static void main(String[] args) throws ClassNotFoundException, IOException, SQLException {

        Properties info = new Properties();
        info.load(new FileInputStream("src\\jdbc.properties"));
        String user = info.getProperty("user");
        String password = info.getProperty("password");
        String driver = info.getProperty("driver");
        String url = info.getProperty("url");
        //1.引入驱动
        Class.forName(driver);
        //2,开始连接
        Connection connection = DriverManager.getConnection(url,user,password);

        System.out.println("连接成功");
                                         

        //3.增删改查
        String sql = "select id,name,sex,borndate from beauty";
        //获取执行sql命令的对象
        Statement statement = connection.createStatement();
        //执行sql语句
        ResultSet set = statement.executeQuery(sql);//执行查询语句,返回一个结果集
        //显示查询结果
        while(set.next()){
            int id = set.getInt(1);
            String name = set.getString(2);
            String sex = set.getString(3);
            Date data = set.getDate(4);
            System.out.println(id+"\t"+name+"\t"+sex+"\t"+data+"\t");}


        //4.关闭连接
        set.close();
        statement.close();
        connection.close();

    }
}

5.5 Statement 和 PrepareStatement 的区别

image-20210808155641742

用到了占位符,预编译:

String sql = "SELECT COUNT(*) FROM admin WHERE username = ? AND `password` = ?";


 
PreparedStatement statement =  connection.prepareStatement(sql);
statement.setString(1,u);
statement.setString(2,p);
ResultSet resultSet = statement.executeQuery();

##5.6 总结JDBC相关API

image-20210808160718438

5.7 编写一个数据库小项目

问题

image-20210808172551940

代码

import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
import java.util.Date;
import java.util.Properties;
import java.util.Scanner;

public class PreparedStatementText {
    public static void main(String[] args) throws Exception {
        Scanner input = new Scanner(System.in);

        Properties info = new Properties();
        info.load(new FileInputStream("src\\jdbc.properties"));
        String user = info.getProperty("user");
        String password = info.getProperty("password");
        String driver = info.getProperty("driver");
        String url = info.getProperty("url");


        Class.forName(driver);

        Connection connection = DriverManager.getConnection(url, user, password);

        System.out.println("连接成功");

//        ------------------1.插入数据--------------------------
        System.out.println("------------------1.插入数据--------------------------");
        System.out.println("请输入编号:");
        String bh = input.next();
        System.out.println("请输入姓名:");
        String xm = input.next();
        System.out.println("请输入邮箱:");
        String yx = input.next();
        System.out.println("请输入生日:");
        String sr = input.next();


        String sql1 = "insert into customers VALUES (?,?,?,?,?)";
        PreparedStatement statement1 = connection.prepareStatement(sql1);
        statement1.setString(1,bh);
        statement1.setString(2,xm);
        statement1.setString(3,yx);
        statement1.setString(4,sr);
        statement1.setString(5,"null");
        int result = statement1.executeUpdate();
        if(result != 0){
            System.out.println("插入成功");
        }else {
            System.out.println("插入失败");
        }

//-------------------2.修改指定客户---------------------------------
        System.out.println("-------------------2.修改指定客户---------------------------------");
        System.out.println("请输入待修改的客户编号");
        String bh2 = input.next();
        System.out.println("请输入新的客户姓名");
        String xm2 = input.next();

        String sql2 = "UPDATE `customers` SET `name` = ? WHERE `id` = ?";
        PreparedStatement statement2 = connection.prepareStatement(sql2);//生成命令
        statement2.setString(1,xm2);
        statement2.setString(2,bh2);
        int result2 = statement2.executeUpdate(); //执行命令,不需要插入sql语句
        if(result2 !=0){
            System.out.println("插入成功");
        }else {
            System.out.println("插入失败");
        }


//        --------------------3.查询所有客户信息-------------------

        System.out.println("开始查询所有用户信息:");
        System.out.println("----------------------------");

        String sql3 = "select id,name,email,birth from customers";
        PreparedStatement statement3 = connection.prepareStatement(sql3);
        ResultSet resultSet = statement3.executeQuery();
        while(resultSet.next()){
            int id = resultSet.getInt(1);
            String name = resultSet.getString(2);
            String email = resultSet.getString(3);
            Date date = resultSet.getDate(4);
            System.out.println("id:"+id+"\t"+"name:"+name+"\t"+"email:"+email+"\t"+"birth:"+date);
        }


//        -----------------------4.根据编号查询-----------------------
        System.out.println(" -----------------------4.根据编号查询-----------------------");

        System.out.println("请输入编号:");
        String bh4 = input.next();
        String sql4 = "SELECT id,NAME,email,birth FROM `customers` WHERE id = ?";
        PreparedStatement statement4 = connection.prepareStatement(sql4);
        statement4.setString(1,bh4);
        ResultSet resultSet1 = statement4.executeQuery();
        if(resultSet1.next()){
            int id4 = resultSet1.getInt(1);
            String name4 = resultSet1.getString(2);
            String email4 = resultSet1.getString(3);
            Date date4 = resultSet1.getDate(4);
            System.out.println("------------------------");
            System.out.println("\t"+"编号"+"\t"+"姓名"+"\t"+"邮箱"+"\t"+"生日");
            System.out.println("\t"+id4+"\t"+name4+"\t"+email4+"\t"+date4);
        }

//        --------------------------5.根据姓名查询----------------------
        System.out.println(" --------------------------5.根据姓名查询----------------------");
        System.out.println("请输入姓名:");
        String xm5 = input.next();
        String sql5 = "SELECT id,NAME,email,birth FROM `customers` WHERE name = ?";
        PreparedStatement statemen5 = connection.prepareStatement(sql5);
        statement4.setString(1,xm5);
        ResultSet resultSet2 = statement4.executeQuery();
        if(resultSet2.next()){
            int id5 = resultSet.getInt(1);
            String name5 = resultSet.getString(2);
            String email5 = resultSet.getString(3);
            Date date5 = resultSet.getDate(4);
            System.out.println("------------------------");
            System.out.println("\t"+"编号"+"\t"+"姓名"+"\t"+"邮箱"+"\t"+"生日");
            System.out.println("\t"+id5+"\t"+name5+"\t"+email5+"\t"+date5);
        }else{
            System.out.println("------------------------");
            System.out.println("查无此人");
        }
         statement1.close();
        statement2.close();
        statement3.close();
        statement4.close();
        statemen5.close();
        connection.close();
    }
}

结果

image-20210808172505605

image-20210808172516289

5.8——JDBCUtils的创建

####创建

:抛出运行异常。

import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JDBCUtils {
//---------------------------------------------------------
    static String user;
    static String password;
    static String driver;
    static String url;
    static {
        try {
            Properties info = new Properties();
            info.load(new FileInputStream("src\\jdbc.properties"));
            user = info.getProperty("user");
            password = info.getProperty("password");
            driver = info.getProperty("driver");
            url = info.getProperty("url");
            Class.forName(driver);
        } catch (Exception e) {
           throw new RuntimeException(e);
        }
    }
    
    
    public static Connection getConnection () throws Exception {//用于注册驱动,连接数据库
        try{
            System.out.println("连接成功");
            return DriverManager.getConnection(url, user, password);
        } catch (Exception e){
            throw new RuntimeException(e);
        }
    }
//----------------------------------------------------------------
    public static void close(ResultSet set , Statement state, Connection connection) throws SQLException {
        try{
            if(set !=null){
                set.close();
            }
            if(state != null){
                state.close();
            }
            if(connection !=null){
                connection.close();
            }
        } catch (Exception e){
            throw new RuntimeException(e);
        }
    }
}

标准的数据库写法

image-20210809153116441

5.9——JDBC的事务处理

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

public class TestTransaction {
    public static void main(String[] args) {
            Connection connection = null;
            PreparedStatement statement = null;
            try {
//            连接数据库
                connection = JDBCUtils.getConnection();
//            1.启动事务
                connection.setAutoCommit(false);
//            2.编写sql语句
//            操作1:
                String sql = "update account set balance =? where username =?";
                statement = connection.prepareStatement(sql);
                statement.setDouble(1,5000);
                statement.setString(2,"冯绍峰");
                statement.executeUpdate();
//            操作2:
                statement.setDouble(1,15000);
                statement.setString(2,"赵丽颖");
                statement.executeUpdate();
//            3.结束事务
                connection.commit();
            } catch (Exception e) {
                try {
                    connection.rollback(); //事务回滚
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            } finally { //最后无论如何都关闭数据库
                try {
                    JDBCUtils.close(null,statement,connection);
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }

5.10——演示批处理

:首先需要更改url:?rewriteBatchedStatements=true(添加在后面就行)

**API:**

addBatch(); 添加sql语句

executeBatch(); 执行sql语句包

clearBatch(); 清空sql语句包
import java.sql.Connection;
import java.sql.PreparedStatement;

public class TestBact{
    public static void main(String[] args) throws Exception {
        Connection connection = JDBCUtils.getConnection();
        PreparedStatement statement = connection.prepareStatement("insert into admin values(?,?,?)");

        for (int i = 1; i < 50000; i++) {
            statement.setInt(1,i+2);
            statement.setString(2,"john"+i);
            statement.setString(3,"0000");

            statement.addBatch(); //添加语句
            if(i%1000 == 0){  //当到1000时执行一次
                statement.executeBatch();//执行批处理包中的sql语句
                statement.clearBatch();//清空批处理包中的sql语句
            }
        }

    }
}

5.11——数据库连接池

必要性

image-20210809170303344

配置properties

#key=value

driverClassName=com.mysql.jdbc.Driver

url=jdbc:mysql://localhost:3306/bookstore?rewriteBatchedStatements=true

#url=jdbc:mysql://localhost:3306/mysqldb

username=root
password=123456
initialSize=10

minIdle=5
maxActive=20

maxWait=5000
其中:

minIdle 限制连接池最保存、剩余的最小连接数;

macActive 是最大连接数;

API

properties.load(new FileInputStream("src\\druid.properties"));

DataSource source = DruidDataSourceFactory.createDataSource(properties);

代码

import com.alibaba.druid.pool.DruidAbstractDataSource;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.util.Properties;

public class TestDataSource {
    public static void main(String[] args) throws Exception {
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\druid.properties"));
//        创建一个指定数值的连接池
        DataSource source = DruidDataSourceFactory.createDataSource(properties);
//        从连接池中获取一个连接对象
        Connection connection = source.getConnection();

        System.out.println("连接成功");

//        关闭连接
        connection.close();
    }
}

Durid_JDBCUtils

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JDBCUtilsbyDruid {
    static DataSource source;
    static {  //只在调用第一次的时候执行
        try {
            Properties properties = new Properties();
            properties.load(new FileInputStream("src\\druid.properties"));
            //        创建一个指定数值的连接池
            DataSource source = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() throws SQLException {
        //        从连接池中获取一个连接对象

            System.out.println("连接成功");
            return source.getConnection();
    }




//        关闭连接
public static void close(ResultSet set , Statement state, Connection connection) throws SQLException {
    try{
        if(set !=null){
            set.close();
        }
        if(state != null){
            state.close();
        }
        if(connection !=null){
            connection.close();
        }
    } catch (Exception e){
        throw new RuntimeException(e);
    }
}
}