1. 程式人生 > >Mysql開啟遠端連線(新增遠端連線使用者)

Mysql開啟遠端連線(新增遠端連線使用者)

在預設情況下,mysql是禁止遠端連線的,而伺服器又不是隨隨便便就要登入的,所以就要開啟遠端連線。
開啟資料庫遠端連線的時候,記得要把伺服器的安全組也開放資料庫的埠(mysql預設3306),不然也會出現無法訪問的情況

建立遠端連線資料庫的使用者

  1. 登入mysql

    [root@VM_149_46_centos etc]# mysql -u root -p
    Enter password: 
    Welcome to the MySQL monitor.  Commands end with ; or \g.
    Your MySQL connection id is 15
    Server version
    : 5.7.21 MySQL Community Server (GPL) Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Type 'help;' or '\h' for help. Type '\c' to clear the
    current input statement.
  2. 建立遠端連線使用者

    mysql> use mysql
    Reading table information for completion of table and column names
    You can turn off this feature to get a quicker startup with -A
    
    Database changed
    
    mysql> CREATE USER 'cwm'@'%' IDENTIFIED BY 'Cwmniwo,1';
    Query OK, 0 rows affected (0.01 sec)

    為使用者建立一個數據庫試試

    mysql> CREATE DATABASE cwm1 DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
    Query OK, 1 row affected (0.00 sec)
  3. 授權

    mysql> GRANT ALL PRIVILEGES ON `cwm1`.* TO 'cwm'@'%' ;
    Query OK, 0 rows affected (0.00 sec)
    
    mysql> FLUSH PRIVILEGES;
    Query OK, 0 rows affected (0.00 sec)
  4. 測試

    mysql> exit;
    Bye
    [root@VM_149_46_centos etc]# mysql -u cwm -p
    Enter password: 
    Welcome to the MySQL monitor.  Commands end with ; or \g.
    Your MySQL connection id is 16
    Server version: 5.7.21 MySQL Community Server (GPL)
    
    Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.
    
    Oracle is a registered trademark of Oracle Corporation and/or its
    affiliates. Other names may be trademarks of their respective
    owners.
    
    Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
    
    mysql> show databases;
    +--------------------+
    | Database           |
    +--------------------+
    | information_schema |
    | cwm1               |
    +--------------------+
    2 rows in set (0.00 sec)

    已經連線成功並可以查詢,經過測試,本地使用navicat也可以連線。

以下是修改配置檔案達到目的的步驟(請檢視參考連線進行配置)

  1. 查詢配置檔案在哪裡
    先要查詢資料庫安裝在了哪裡

    [root@VM_149_46_centos etc]# which mysqld
    /usr/sbin/mysqld

    這裡可以得到資料庫安裝在了/usr/sbin/mysqld

    [root@VM_149_46_centos etc]# /usr/sbin/mysqld --verbose --help | grep -A 1 'Default options'
    Default options are read from the following files in the given order:
    /etc/my.cnf /etc/mysql/my.cnf /usr/etc/my.cnf ~/.my.cnf 

    這裡可以得出配置檔案的地址在 /etc/my.cnf/etc/mysql/my.cnf/usr/etc/my.cnf~/.my.cnf

  2. 修改配置檔案
  3. 重啟資料庫服務
  4. 測試