mysql knowledge point over again

mysql installation

1 mysql installation package , it is strongly not recommended to install mysql8 version, mysql does not have 6 and 7 versions, the last version is mysql v5.7

2 Unzip to the c drive to find the path

3 Configure the mysql bin directory to the system variable path

4 Modify the configuration file defautl, ini

basedir = C:\Program Files\mysql-5.7.14\bin
datadir = C:\Program Files\mysql-5.7.14\bin\data

5 Find the mysql installation directory, rename its configuration file my.default.ini to my.ini, and move my.ini to the bin directory

6 cmd command to enter the bin directory

mysqld -install	   // 注册mysql 服务
mysqld -initialize // 启动,建立data目录
net start mysql    // 启动mysql服务

7. When installing the mysql5.7 version, you often encounter the situation that mysql -u root -p can't log in directly. The reason is that the 5.7 version automatically gave a random password, mysql/data*.err, during installation. Find the password, after login, modify
set password for root@localhost = password('123');

8 Start mysq v8 cmd and enter services.msc to find mysql80 and then start

mac mysql login

After the default installation is complete, it is impossible to log in, just perform the following steps.

cd /usr/local/mysql/bin/ 
sudo ./mysqld_safe --skip-grant-tables

// 然后新开一个ternimal
 cd /usr/local/mysql/bin/
 ./mysql 
 flush privileges;
 set password for 'root@localhost'= password('123456');

Database connection pool (connection pool)

1. Use database connection pool technology to solve the problems caused by frequent allocation and release of resources

2. The database connection pool is to establish a "buffer pool" for database connections. A certain number of connections are placed in the buffer pool in advance. When a database connection needs to be established, one only needs to be taken out of the "buffer pool". put it back. We can prevent the system from endlessly connecting to the database by setting the maximum number of connections in the connection pool

Transaction
Database transaction is a collection of operations that constitute a single logical unit of work. Transactions enable the system to more easily perform failure recovery and concurrency control, thereby ensuring the consistency of database status

BEGIN TRANSACTION  //事务开始
SQL1 ~~~
SQL2 ~~~
COMMIT/ROLLBACK   //事务提交或回滚

1. A database transaction can contain one or more database operations, but these operations constitute a logical whole
2. These database operations that constitute a logical whole are either executed successfully or not executed at all, and the database can always maintain a consistent state
3 .It is still true when the database fails and concurrent transactions exist

Transaction characteristics

1. Atomicity: All operations in a transaction are as indivisible as atoms as a whole, either all succeed or all fail.
Consistency (Consistency): The execution result of the transaction must make the database from a consistent state to another consistent state. The consistency state refers to: 1. The state of the system satisfies the integrity constraints of the data (master code, referential integrity, check constraints, etc.) 2. The state of the system reflects the real state of the real world that the database should describe, such as before and after the transfer The sum of the amounts of each account should remain unchanged.
3. Isolation (Isolation): concurrently executed transactions will not affect each other, and its impact on the database is the same as when they are executed serially. For example, if multiple users transfer money to one account at the same time, the result of the final account should be the same as the result of their transfer in order.
4. Durability: Once a transaction is committed, its update to the database is durable. Any transaction or system failure will not cause data loss. The
database system uses concurrency control technology and log recovery technology to avoid damage to data consistency (concurrent execution of transactions, transaction failures or system failures)

The classification of the
transaction shows the transaction : use BEGIN TRANSACTION to clearly specify the beginning of the transaction, which is the most commonly used transaction type

Implicit transaction : Set the implicit transaction mode to open by setting the SET IMPLICIT_TRANSACTIONS ON statement, and the next statement automatically starts a new transaction. When the transaction is completed, the next T-SQL statement will start a new transaction

Auto-commit transaction : This is the default mode of SQL Server, it treats each individual T-SQL statement as a transaction, if it is executed successfully, it will be automatically committed; if it is wrong, it will be automatically rolled back

Transaction sql code
BEGIN TRANSACTION 
/*--定义变量,用于累计事务执行过程中的错误--*/
DECLARE @errorSum INT 
SET @errorSum=0  --初始化为0,即无错误
/*--转账:张三的账户少1000元,李四的账户多1000元*/
UPDATE bank SET currentMoney=currentMoney-1000
   WHERE customerName='张三'
SET @errorSum=@errorSum+@@error
UPDATE bank SET currentMoney=currentMoney+1000
   WHERE customerName='李四'
SET @errorSum=@errorSum+@@error  --累计是否有错误
IF @errorSum<>0  --如果有错误
  BEGIN
    print '交易失败,回滚事务'
    ROLLBACK TRANSACTION 
  END  
ELSE
  BEGIN
    print '交易成功,提交事务,写入硬盘,永久的保存'
    COMMIT TRANSACTION   
  END
GO
print '查看转账事务后的余额'
SELECT * FROM bank  

index

Index optimization should be the most effective means for query performance optimization, because the index greatly reduces the amount of data that the server needs to scan.
MySQL can only use the leftmost prefix column
of the index efficiently. The index in MySQL is implemented at the storage engine layer instead of the server layer.
Indexes can help servers avoid sorting and temporary tables.
Indexes can turn random I/O into sequential I/O

view

A view is a virtual table , which represents part of the data of a table or the comprehensive data of multiple tables. Its structure and data are based on the query of the table. The advantages of using the view:
1. Play a role of authority control, Only the data that can be seen
2. Improve performance, prevent multi-table join query
3. Flexible, table and view mapping, more flexible

// 查询表会显示视图
SHOW tables
// 创建视图 
create view view1 as select * from people;
// 删除视图
DROP VIEW IF EXISTS v_students_info;

Stored procedure

A stored procedure is a set of SQL statements in a large database system in order to complete a specific function, which is compiled and stored in the database. The user specifies the name of the stored procedure and gives parameters (if the stored procedure has parameters) to execute It features:
1. Faster execution speed
2. Modular programming
3. Improve system security
4. Reduce network traffic.
Advantages:
1. Encapsulate some highly repetitive operations into a storage process , Simplifies the call to these SQL
2. Batch processing: SQL + loop, reduce traffic, that is, run batch
3. Unified interface to ensure data security
MySQL 5.0 version began to support stored procedures, compared to Oracle database, MySQL storage The process is relatively weak and less used


java connect mysql

1. Add the package in maven

<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>5.1.25</version>
</dependency>

2. Code

ublic class MysqlTest {
    
    
  // MySQL 8.0 以下版本 - JDBC 驱动名及数据库 URL
  static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
  static final String DB_URL = "jdbc:mysql://localhost:3306/hua";
  static final String USER = "root";
  static final String PASS = "123";

  public static void main(String[] args) throws ClassNotFoundException, SQLException {
    
    
    Connection connect = null;
    Statement stmt = null;

    Class.forName(JDBC_DRIVER);
    System.out.println("连接数据库~~~");
    connect = DriverManager.getConnection(DB_URL,USER,PASS);

    // 执行查询
    System.out.println(" 实例化Statement对象...");
    stmt = connect.createStatement();

    String sql;
    sql = "SELECT id, name FROM people";
    ResultSet rs = stmt.executeQuery(sql);

    // 展开结果集数据库
    while(rs.next()){
    
    
      int id  = rs.getInt("id");
      String name = rs.getString("name");
      // 输出数据
      System.out.println("id=" + id + "&name=" + name);
    }
    // 完成后关闭
    rs.close();
    stmt.close();
    connect.close();
  }
}

View port number

mysql -u root -p
SHOW global variables like 'port';

type of data

1 Integer The five main integer types supported in MySQL are TINYINT, SMALLINT, MEDIUMINT, INT and BIGINT. Unsigned can be added, and the maximum value is doubled

int(3) // 1999显示1999  12显示 012 

2 Decimal FLOAT(7,3) specifies that the displayed value will not exceed 7 digits
FLOAT, DOUBLE and DECIMAL,

3 int(3), int(4), and int(8) all occupy 4 btyes of storage space on the disk bai. To put it bluntly, except for the way it is displayed to the user is a bit different, the int(M) and int data types are the same.


Database operation

// 查看数据库
SHOW databases;
SHOW schemas;

//创建数据库
create schema hua;
create database hua;

// 使用数据库
use hua; 

//删除数据库
DROP database hua;

//查看数据库信息
SHOW create database hua;

Display the names of all tables in the current database

SHOW tables;//显示当前数据库的所有的表        
SHOW tables from database_name;//显示某个数据库的所有的表

Table operation

//显示多少表
SHOW tables;

//创建表
create table huahua1(
    id int auto_increment,
    name varchar(25)
)

//修改表名
ALTER table huahua1 rename hua1;

//修改表的引擎
ALTER table engine InnoDB;

//查看表的结构
desc hua1;

// 看表的所有列
SHOW columns from table_name from database_name;
SHOW columns from database_name.table_name;

//修改表的列,可以添加约束 
ALTER table hua1 modify id int(10);

// 改变列的位置
ALTER table hua1 modify sex int(1) after name;

// 修改列的名称
ALTER table hau1 change salary sal float;

// 添加新的列
ALTER table hua1 add sex int(0) default 0;

// 指定位置的字段,有first
ALTER table hua1 add hobby varchar(20) after sal;

//删除字段
ALTER table hua1 drop hobby;
ALTER table hua1 drop column hobby;

SELECT


SELECT name from cup; //查1行
SELECT name,age from cup; //查2行
SELECT * from cup; //查所有行

------ ------ ------ ------ ------ ------ ------ ------

@限制查询返回的数量
SELECT * from cup limit 2; //只要前两条 
SELECT * from cup limit 2 offset 1  ; //从第1条开始取2条

------ ------ ------ ------ ------ ------ ------ ------

@条件判断
SELECT * from cup where id = 1;
SELECT * from cup where id > 1;
SELECT * from cup where id >= 1;
SELECT * from cup where id < 1;

------ ------ ------ ------ ------ ------ ------ ------

@范围筛选 
// id 1,2,3都可以
SELECT * from cup where id in (1,2,3);
// id 不是1,2,3都可以 
SELECT * from cup where id not in (1,2,3);

// id 大于1,2,3 的所有,就是大于全部才可以 
SELECT * from cup where id > all  (1,2,3);
SELECT * from cup where id >= all (SELECT id from cup);
 
// id 大于1,2,3中的1个就可以和下边一句是一样的 some和any一样用 
SELECT * from cup where id > some  (1,2,3);
SELECT * from cup where id > 1 or id > 2 or id > 3;

------ ------ ------ ------ ------ ------ ------ ------

@合并结果 union会删除重复的数据,union all不会删除重复的 
// cup1和cup2的字段必须一样,如果不一样就合并一样的
SELECT * from cup1 union SELECT * from cup2;

@模糊查询
SELECT name from cup where name LIKE "hua%"; // hua开头的
SELECT name from cup where name LIKE "%hua%"; // 中间有hua的 

@排序 order by
select * from user1 order by age;

------ ------ ------ ------ ------ ------ ------ ------

@计算
// 查询最高工资
select max(money) from user2;
// 查询最低工资
select min(money) from user2;
// 查询平均工资
select avg(money) from user2;

------ ------ ------ ------ ------ ------ ------ ------

@分组 分组一般配合计算 
// 按年龄分组的工资 
select age, AVG(money) from user2 group by age;
// 每个年龄段的最高工资
select age, MAX(money) from user2 group by age;
// 每个年龄段有多少人
select age, count(*) from user2 group by age;

@统计 查看表中年龄范围 
select count(*) from user1 where age > 17 and age < 30;


constraint

Primary key constraint primary key is not empty and unique

create table huahua1(
    id int(11) primary key,
    name varchar(25)
)

// 添加唯一约束
alter table student add unique(card_id);

// 增主键约束
ALTER table cup add primary key(id); 
ALTER table cup drop primary key;  

// 添加外键对应的列要是主键
alter table student add foreign key (card_id) references student_card(id);

// 可以多个值做成主键 
primary key(name,deptid)


Mysql adds foreign keys! !

CREATE TABLE teacher(
    t_id INT PRIMARY KEY AUTO_INCREMENT,
    t_name VARCHAR(20)
);
CREATE TABLE class(
    c_id INT PRIMARY KEY AUTO_INCREMENT,
    c_name VARCHAR(20),
    teacher_id INT
);
ALTER TABLE class ADD CONSTRAINT fk_teacher_id FOREIGN KEY (teacher_id) REFERENCES teacher(t_id);

JOIN usage

Roughly divided into internal connection, external connection, right connection, left connection, natural connection
Insert picture description here

Other related

SHOW grants; // 查看权限 
SHOW index from table; //查看索引
SHOW engines; // 显示安装以后可用的存储引擎和默认引擎。

Reference

(https://www.cnblogs.com/takumicx/p/9998844.html)
(https://www.cnblogs.com/beili/p/9140019.html)

Guess you like

Origin blog.csdn.net/qq_29334605/article/details/107300798