Instalação de MySQL em Ubuntu

Bases de Dados (CC2005), Dep. Ciência de Computadores, FCUP

Eduardo R. B. Marques, DCC/FCUP

Estas instruções foram testadas em Ubuntu 18.04 LTS mas deverão funcionar para outras versões recentes do Ubuntu e outras distribuições Linux.

1. Já está instalado?

Execute mysqld --version para verificar se já tem o servidor MySQL instalado.

$ mysqld --version
mysqld  Ver 5.7.29-0ubuntu0.18.04.1 for Linux on x86_64 ((Ubuntu))

Se obtiver uma mensagem do género ilustrado acima, salte para o passo 3.

2. Não está instalado!

Execute

sudo apt update

e depois

sudo apt install mysql-server

Teste se o MySQL ficou instalado de novo usando

mysqld --version

3. Configuração base

Execute

sudo mysql_secure_installation

Serão feitas várias perguntas, das quais a mais importante se refere à password do utilizador root (administrador). Para um ambiente simples de desenvolvimento, sugere-se a configuração ilustrada abaixo.

Caso tenha problema, deverá poder executar o passo 4 de qualquer forma a seguir com sucesso.

Securing the MySQL server deployment.

Connecting to MySQL using a blank password.

VALIDATE PASSWORD PLUGIN can be used to test passwords
and improve security. It checks the strength of password
and allows the users to set only those passwords which are
secure enough. Would you like to setup VALIDATE PASSWORD plugin?

Press y|Y for Yes, any other key for No: n

...

Please set the password for root here.

New password: <defina a password>

Re-enter new password: <confirme password>

...
By default, a MySQL installation has an anonymous user,
allowing anyone to log into MySQL without having to have
a user account created for them. This is intended only for
testing, and to make the installation go a bit smoother.
You should remove them before moving into a production
environment.

Remove anonymous users? (Press y|Y for Yes, any other key for No) : y
Success.


Normally, root should only be allowed to connect from
'localhost'. This ensures that someone cannot guess at
the root password from the network.

Disallow root login remotely? (Press y|Y for Yes, any other key for No) : y
Success.

By default, MySQL comes with a database named 'test' that
anyone can access. This is also intended only for testing,
and should be removed before moving into a production
environment.


Remove test database and access to it? (Press y|Y for Yes, any other key for No) : n

 ... skipping.
Reloading the privilege tables will ensure that all changes
made so far will take effect immediately.

Reload privilege tables now? (Press y|Y for Yes, any other key for No) : y
Success.

4. Adicione utilizador da BD

Para EVITAR ligar-se ao MySQL como root e/ou usando sudo precisamos de criar um utilizador.

Para tal execute sudo mysql (pela última vez!) e configure um utilizador como ilustrado abaixo. No exemplo o utilizador chama-se guest. Pode escolher outro nome; usa-se aqui guest por coerência com o ambiente dos laboratórios do DCC.

Abaixo substitua 'pass' pela password que quiser para o utilizador guest.

edrdo@mysql:~$ sudo mysql
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 6
Server version: 5.7.29-0ubuntu0.18.04.1 (Ubuntu)
...

mysql> CREATE USER 'guest'@'localhost' IDENTIFIED BY 'pass';
Query OK, 0 rows affected (0.00 sec)

mysql> GRANT ALL PRIVILEGES ON *.* TO 'guest'@'localhost' WITH GRANT OPTION;
Query OK, 0 rows affected (0.00 sec)

mysql> exit
Bye

5. Teste acesso por utilizador

SEM USAR sudo execute agora:

mysql -uguest -p

Ser-lhe-á pedido a password para o utilizador guest (ou para o utilizador que preferiu definir):

Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 12
Server version: 5.7.29-0ubuntu0.18.04.1 (Ubuntu)

Copyright (c) 2000, 2020, 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> 

Na consola MySQL poderá ser então conveniente criar uma base de dados. Novamente para espelhar a convenção dos laboratórios do DCC, abaixo usa-se guest para o nome da base de dados.

mysql> CREATE DATABASE guest;
Query OK, 1 row affected (0.00 sec)

Faça depois um pequeno teste de sanidade:

mysql> USE guest;
Database changed

mysql> CREATE TABLE TEST(Value INT);
Query OK, 0 rows affected (0.07 sec)

mysql> INSERT INTO TEST(Value) VALUES (1), (2), (3);
Query OK, 3 rows affected (0.02 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> SELECT * FROM TEST;
+-------+
| Value |
+-------+
|     1 |
|     2 |
|     3 |
+-------+
3 rows in set (0.01 sec)

mysql> show tables;
+-----------------+
| Tables_in_guest |
+-----------------+
| TEST            |
+-----------------+
1 row in set (0.00 sec)

mysql> DROP TABLE TEST;
Query OK, 0 rows affected (0.01 sec)

mysql> exit
Bye