Sunday, October 6, 2019

How To Install MySQL on Ubuntu 18.04

Introduction

MySQL is an open-source database management system, commonly installed as part of the popular LAMP (Linux, Apache, MySQL, PHP/Python/Perl) stack. It uses a relational database and SQL (Structured Query Language) to manage its data.
The short version of the installation is simple: update your package index, install the mysql-server package, and then run the included security script.
  • sudo apt update
  • sudo apt install mysql-server
  • sudo mysql_secure_installation
This tutorial will explain how to install MySQL version 5.7 on an Ubuntu 18.04 server. However, if you’re looking to update an existing MySQL installation to version 5.7, you can read this MySQL 5.7 update guide instead.

Prerequisites

To follow this tutorial, you will need:

Step 1 — Installing MySQL

On Ubuntu 18.04, only the latest version of MySQL is included in the APT package repository by default. At the time of writing, that’s MySQL 5.7
To install it, update the package index on your server with apt:
  • sudo apt update
Then install the default package:
  • sudo apt install mysql-server
This will install MySQL, but will not prompt you to set a password or make any other configuration changes. Because this leaves your installation of MySQL insecure, we will address this next.

Step 2 — Configuring MySQL

For fresh installations, you’ll want to run the included security script. This changes some of the less secure default options for things like remote root logins and sample users. On older versions of MySQL, you needed to initialize the data directory manually as well, but this is done automatically now.
Run the security script:
  • sudo mysql_secure_installation
This will take you through a series of prompts where you can make some changes to your MySQL installation’s security options. The first prompt will ask whether you’d like to set up the Validate Password Plugin, which can be used to test the strength of your MySQL password. Regardless of your choice, the next prompt will be to set a password for the MySQL root user. Enter and then confirm a secure password of your choice.
From there, you can press Y and then ENTER to accept the defaults for all the subsequent questions. This will remove some anonymous users and the test database, disable remote root logins, and load these new rules so that MySQL immediately respects the changes you have made.
To initialize the MySQL data directory, you would use mysql_install_db for versions before 5.7.6, and mysqld --initialize for 5.7.6 and later. However, if you installed MySQL from the Debian distribution, as described in Step 1, the data directory was initialized automatically; you don’t have to do anything. If you try running the command anyway, you’ll see the following error:
Output
mysqld: Can't create directory '/var/lib/mysql/' (Errcode: 17 - File exists)
. . .
2018-04-23T13:48:00.572066Z 0 [ERROR] Aborting
Note that even though you’ve set a password for the root MySQL user, this user is not configured to authenticate with a password when connecting to the MySQL shell. If you’d like, you can adjust this setting by following Step 3.

Step 3 — (Optional) Adjusting User Authentication and Privileges

In Ubuntu systems running MySQL 5.7 (and later versions), the root MySQL user is set to authenticate using the auth_socket plugin by default rather than with a password. This allows for some greater security and usability in many cases, but it can also complicate things when you need to allow an external program (e.g., phpMyAdmin) to access the user.
In order to use a password to connect to MySQL as root, you will need to switch its authentication method from auth_socket to mysql_native_password. To do this, open up the MySQL prompt from your terminal:
  • sudo mysql
Next, check which authentication method each of your MySQL user accounts use with the following command:
  • SELECT user,authentication_string,plugin,host FROM mysql.user;
Output
+------------------+-------------------------------------------+-----------------------+-----------+ | user | authentication_string | plugin | host | +------------------+-------------------------------------------+-----------------------+-----------+ | root | | auth_socket | localhost | | mysql.session | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE | mysql_native_password | localhost | | mysql.sys | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE | mysql_native_password | localhost | | debian-sys-maint | *CC744277A401A7D25BE1CA89AFF17BF607F876FF | mysql_native_password | localhost | +------------------+-------------------------------------------+-----------------------+-----------+ 4 rows in set (0.00 sec)
In this example, you can see that the root user does in fact authenticate using the auth_socket plugin. To configure the root account to authenticate with a password, run the following ALTER USER command. Be sure to change password to a strong password of your choosing, and note that this command will change the root password you set in Step 2:
  • ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
Then, run FLUSH PRIVILEGES which tells the server to reload the grant tables and put your new changes into effect:
  • FLUSH PRIVILEGES;
Check the authentication methods employed by each of your users again to confirm that root no longer authenticates using the auth_socket plugin:
  • SELECT user,authentication_string,plugin,host FROM mysql.user;
Output
+------------------+-------------------------------------------+-----------------------+-----------+ | user | authentication_string | plugin | host | +------------------+-------------------------------------------+-----------------------+-----------+ | root | *3636DACC8616D997782ADD0839F92C1571D6D78F | mysql_native_password | localhost | | mysql.session | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE | mysql_native_password | localhost | | mysql.sys | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE | mysql_native_password | localhost | | debian-sys-maint | *CC744277A401A7D25BE1CA89AFF17BF607F876FF | mysql_native_password | localhost | +------------------+-------------------------------------------+-----------------------+-----------+ 4 rows in set (0.00 sec)
You can see in this example output that the root MySQL user now authenticates using a password. Once you confirm this on your own server, you can exit the MySQL shell:
  • exit
Alternatively, some may find that it better suits their workflow to connect to MySQL with a dedicated user. To create such a user, open up the MySQL shell once again:
  • sudo mysql
Note: If you have password authentication enabled for root, as described in the preceding paragraphs, you will need to use a different command to access the MySQL shell. The following will run your MySQL client with regular user privileges, and you will only gain administrator privileges within the database by authenticating:
  • mysql -u root -p


From there, create a new user and give it a strong password:
  • CREATE USER 'sammy'@'localhost' IDENTIFIED BY 'password';
Then, grant your new user the appropriate privileges. For example, you could grant the user privileges to all tables within the database, as well as the power to add, change, and remove user privileges, with this command:
  • GRANT ALL PRIVILEGES ON *.* TO 'sammy'@'localhost' WITH GRANT OPTION;
Note that, at this point, you do not need to run the FLUSH PRIVILEGES command again. This command is only needed when you modify the grant tables using statements like INSERTUPDATE, or DELETE. Because you created a new user, instead of modifying an existing one, FLUSH PRIVILEGES is unnecessary here.
Following this, exit the MySQL shell:
  • exit
Finally, let’s test the MySQL installation.

Step 4 — Testing MySQL

Regardless of how you installed it, MySQL should have started running automatically. To test this, check its status.
  • systemctl status mysql.service
You’ll see output similar to the following:
Output
● mysql.service - MySQL Community Server
   Loaded: loaded (/lib/systemd/system/mysql.service; enabled; vendor preset: en
   Active: active (running) since Wed 2018-04-23 21:21:25 UTC; 30min ago
 Main PID: 3754 (mysqld)
    Tasks: 28
   Memory: 142.3M
      CPU: 1.994s
   CGroup: /system.slice/mysql.service
           └─3754 /usr/sbin/mysqld
If MySQL isn’t running, you can start it with sudo systemctl start mysql.
For an additional check, you can try connecting to the database using the mysqladmin tool, which is a client that lets you run administrative commands. For example, this command says to connect to MySQL as root (-u root), prompt for a password (-p), and return the version.
  • sudo mysqladmin -p -u root version
You should see output similar to this:
Output
mysqladmin  Ver 8.42 Distrib 5.7.21, for Linux on x86_64
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.

Server version      5.7.21-1ubuntu1
Protocol version    10
Connection      Localhost via UNIX socket
UNIX socket     /var/run/mysqld/mysqld.sock
Uptime:         30 min 54 sec

Threads: 1  Questions: 12  Slow queries: 0  Opens: 115  Flush tables: 1  Open tables: 34  Queries per second avg: 0.006
This means MySQL is up and running.

Conclusion

Monday, July 16, 2018

How to import an SQL file using the command line in MySQL?

Try:
mysql -u username -p database_name < file.sql
Check MySQL Options.
Note-1: It is better to use the full path of the SQL file file.sql.
Note-2: Use -R and --triggers to keep the routines and triggers of original database. They are not copied by default.
 
---------
A common use of mysqldump is for making a backup of an entire database:
shell> mysqldump db_name > backup-file.sql
You can load the dump file back into the server like this:
UNIX
shell> mysql db_name < backup-file.sql
The same in Windows command prompt:
mysql -p -u [user] [database] < backup-file.sql
PowerShell
C:\> cmd.exe /c "mysql -u root -p db_name < backup-file.sql"
MySQL command line
mysql> use db_name;
mysql> source backup-file.sql;
 
----------
mysql> use db_name;

mysql> SET autocommit=0 ; source the_sql_file.sql ; COMMIT ;
 
 

Thursday, July 12, 2018

Reset password

You can reset the root password by running the server with --skip-grant-tables and logging in without a password by running the following as root (or with sudo):
# service mysql stop
# mysqld_safe --skip-grant-tables &
$ mysql -u root

mysql> use mysql;
mysql> update user set authentication_string=PASSWORD("YOUR-NEW-ROOT-PASSWORD") where User='root';
mysql> flush privileges;
mysql> quit

# service mysql stop
# service mysql start
$ mysql -u root -p
Now you should be able to login as root with your new password.
It is also possible to find the query that reset the password in /home/$USER/.mysql_history or /root/.mysql_history of the user who reset the password, but the above will always work.
Note: prior to MySQL 5.7 the column was called password instead of authentication_string. Replace the line above with
mysql> update user set password=PASSWORD("YOUR-NEW-ROOT-PASSWORD") where User='root';


--
Chus ys

mkdir -p /var/run/mysqld
chown mysql:mysql /var/run/mysqld

Tuesday, May 29, 2018

How can I run an SQL script in MySQL?

If you’re at the MySQL command line mysql> you have to declare the SQL file as source.
mysql> source \home\user\Desktop\test.sql;
 
You have quite a lot of options:
  • use the MySQL command line client: mysql -h hostname -u user database < path/to/test.sql
  • Install the MySQL GUI tools and open your SQL file, then execute it
  • Use phpmysql if the database is available via your webserver
 
 
you can execute mysql statements that have been written in a text file using the following command:
mysql -u yourusername -p"yourpassword" yourdatabase < text_file
 
 

Sunday, December 3, 2017

mysql_secure_installation — Improve MySQL Installation Security

Linux :
# cat /var/log/mysqld.log | grep "A temporary password is generated" (để đọc password)
$ mysql_secure_installation

Thursday, November 2, 2017

Getting Started with MySQL

Abstract
MySQL is the world's most popular open-source database. Despite its powerful features, MySQL is simple to set up and easy to use. Below are some instructions to help you get MySQL up and running in a few easy steps. We also explain how to perform some basic operations with MySQL using the mysql client.
Notes
  • The following instructions are for MySQL Community Server 5.7 and do not necessarily apply to earlier or other versions of MySQL.
  • These are instructions for a fresh installation only. If you are already using MySQL and want to upgrade to a newer version, see Upgrading MySQL.
For legal information, see the Legal Notices.
For help with using MySQL, please visit either the MySQL Forums or MySQL Mailing Lists, where you can discuss your issues with other MySQL users.
For additional documentation on MySQL products, including translations of the documentation into other languages, and downloadable versions in variety of formats, including HTML and PDF formats, see the MySQL Documentation Library.
Document generated on: 2017-11-02 (revision: 54597)

Table of Contents     


Installing and Starting MySQL

There are different ways to install MySQL. The following covers the easiest methods for installing and starting MySQL on different platforms.

Connecting to the MySQL Server with the mysql Client

Once your MySQL server is up and running, you can connect to it as the superuser root with the mysql client.
  • On Linux, enter the following command at the command line terminal (for installation using generic binaries, you might need to go first to the bin folder under the base directory of your MySQL installation):
    shell> mysql -u root -p
  • On Windows, click Start, All Programs, MySQL, MySQL 5.7 Command Line Client. If you did not install MySQL with the MySQL Installer, open a command prompt, go to the bin folder under the base directory of your MySQL installation, and issue the following command:
    C:\> mysql -u root -p
You are then asked for the root password, which was assigned in different manners according to the way you installed MySQL. The installation and initialization instructions given above already explain the root password, but here is a quick summary:
  • For installations using the MySQL Yum repository, MySQL SUSE repository, or RPM packages directly downloaded from Oracle, the generated root password is in the error log. View it with, for example, the following command:
    shell> sudo grep 'temporary password' /var/log/mysqld.log
  • For installations using the MySQL APT repository or Debian packages directly downloaded from Oracle, you should have already assigned the root password yourself; if you have not done that for some reason, see the "Important" note here or How to Reset the Root Password.
  • For installations on Linux using the generic binaries followed by a data directory initialization using mysqld --initialize as discussed in Initializing the Data Directory Manually Using mysqld, the generated root password is displayed in the standard error stream during the data directory's initialization:
    [Warning] A temporary password is generated for root@localhost:
    iTag*AfrH5ej
    Note
    Depending on the configuration you used to initialize the MySQL server, the error output might have been directed to the MySQL error log; go there and check for the password if you do not see the above message on your screen. The error log is a file with a .err extension, usually found under the server's data directory (the location of which depends on the server's configuration, but is likely to be the data folder under the base directory of your MySQL installation, or the /var/lib/mysql folder).
    If you have initialized the data directory with mysqld --initialize-insecure instead, the root password is empty.
  • For installations on Windows using the MySQL Installer and OS X using the installer package, you should have assigned a root password yourself.
If you have forgotten the root password you have chosen or have problems finding the temporary root password generated for you, see How to Reset the Root Password.
Once you are connected to the MySQL server, a welcome message is displayed and the mysql> prompt appears, at which SQL statements are to be sent to the server for execution:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 5.7.13 MySQL Community Server (GPL)

Copyright (c) 2000, 2016, 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>
At this point, if you have logged in using a temporary root password that was generated during the installation or initialization process (which will be the case if you installed MySQL using the MySQL Yum repository, or using RPM packages or generic binaries from Oracle), reset your root password with the following statement:
mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_password';
Until you reset your root password, you will not be able to exercise any of the superuser privileges, even if you are logged in as root.
Here are a few useful things to remember when using the mysql client:
  • Client commands (for example, help, quit, and clear) and keywords in SQL statements (for example, SELECT, CREATE TABLE, and INSERT) are case insensitive.
  • Column names are case sensitive. Table names are case sensitive on most Unix-like platforms, but case insensitive on Windows platforms. Case sensitivity during string comparison depends on the character collation you use. In general, it is a good idea to treat all identifiers (database names, table names, column names, etc.) and strings as case sensitive. See Identifier Case Sensitivity and Case Sensitivity in String Searches for details.
  • You can type your SQL statements in multiple lines by pressing Enter in the middle of it. Typing a semi-colon (;) followed by an Enter ends an SQL statement and sends it to the server for execution; the same happens when a statement is ended with \g or \G (with the latter, returned results are displayed vertically). However, client commands (for example, help, quit, and clear) do not require a terminator.
To disconnect from the MySQL server, type QUIT or \q at the client:
mysql> QUIT

Some Basic Operations with MySQL

Here are some basic operations with the MySQL server. SQL Statement Syntax explains in detail the rich syntax and functionality of the SQL statements that are illustrated below.
Showing existing databases.  Use a SHOW DATABASES statement:
mysql> SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.00 sec)
Creating a new database.  Use a CREATE DATABASE statement:
mysql> CREATE DATABASE pets;
Query OK, 1 row affected (0.01 sec)
Check if the database has been created:
mysql> SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| pets               |
| sys                |
+--------------------+
5 rows in set (0.00 sec)
Creating a table inside a database.  First, pick the database in which you want to create the table with a USE statement:
mysql> USE pets
Database changed
The USE statement tells MySQL to use pets as the default database for subsequent statements. Next, create a table with a CREATE TABLE statement:
CREATE TABLE cats
(
  id              INT unsigned NOT NULL AUTO_INCREMENT, # Unique ID for the record
  name            VARCHAR(150) NOT NULL,                # Name of the cat
  owner           VARCHAR(150) NOT NULL,                # Owner of the cat
  birth           DATE NOT NULL,                        # Birthday of the cat
  PRIMARY KEY     (id)                                  # Make the id the primary key
);
Data types you can use in each column are explained in Data Types. Primary Key Optimization explains the concept of a primary key. What follows a # on each line is a comment, which is ignored by the mysql client; see Comment Syntax for other comment styles.
Check if the table has been created with a SHOW TABLES statement:
mysql> SHOW TABLES;
+----------------+
| Tables_in_pets |
+----------------+
| cats           |
+----------------+
1 row in set (0.00 sec)
DESCRIBE shows information on all columns of a table:
mysql> DESCRIBE cats;
+-------+------------------+------+-----+---------+----------------+
| Field | Type             | Null | Key | Default | Extra          |
+-------+------------------+------+-----+---------+----------------+
| id    | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| name  | varchar(150)     | NO   |     | NULL    |                |
| owner | varchar(150)     | NO   |     | NULL    |                |
| birth | date             | NO   |     | NULL    |                |
+-------+------------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
Adding records into a table.  Use, for example, an INSERT...VALUES statement:
INSERT INTO cats ( name, owner, birth) VALUES
  ( 'Sandy', 'Lennon', '2015-01-03' ),
  ( 'Cookie', 'Casey', '2013-11-13' ),
  ( 'Charlie', 'River', '2016-05-21' );
See Literal Values for how to write string, date, and other kinds of literals in MySQL.
Retrieving records from a table.  Use a SELECT statement, and * to match all columns:
mysql> SELECT * FROM cats;
+----+---------+--------+------------+
| id | name    | owner  | birth      |
+----+---------+--------+------------+
|  1 | Sandy   | Lennon | 2015-01-03 |
|  2 | Cookie  | Casey  | 2013-11-13 |
|  3 | Charlie | River  | 2016-05-21 |
+----+---------+--------+------------+
3 rows in set (0.00 sec)
To select specific columns and rows by a certain condition using the WHERE clause:
mysql> SELECT name FROM cats WHERE owner = 'Casey';
+--------+
| name   |
+--------+
| Cookie |
+--------+
1 row in set (0.00 sec)
Deleting a record from a table.  Use a DELETE statement to delete a record from a table, specifying the criterion for deletion with the WHERE clause:
mysql> DELETE FROM cats WHERE name='Cookie';
Query OK, 1 row affected (0.05 sec)

mysql> SELECT * FROM cats;
+----+---------+--------+------------+
| id | name    | owner  | birth      |
+----+---------+--------+------------+
|  1 | Sandy   | Lennon | 2015-01-03 |
|  3 | Charlie | River  | 2016-05-21 |
+----+---------+--------+------------+
2 rows in set (0.00 sec)
Adding or deleting a column from a table.  Use an ALTER TABLE...ADD statement to add a column. You can use, for example, an AFTER clause to specify the location of the new column:
mysql> ALTER TABLE cats ADD gender CHAR(1) AFTER name;
Query OK, 0 rows affected (0.24 sec)
Records: 0  Duplicates: 0  Warnings: 0
Use DESCRIBE to check the result:
mysql> DESCRIBE cats;
+--------+------------------+------+-----+---------+----------------+
| Field  | Type             | Null | Key | Default | Extra          |
+--------+------------------+------+-----+---------+----------------+
| id     | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| name   | varchar(150)     | NO   |     | NULL    |                |
| gender | char(1)          | YES  |     | NULL    |                |
| owner  | varchar(150)     | NO   |     | NULL    |                |
| birth  | date             | NO   |     | NULL    |                |
+--------+------------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)
SHOW CREATE TABLE shows a CREATE TABLE statement, which provides even more details on the table:
mysql> SHOW CREATE TABLE cats\G
*************************** 1. row ***************************
       Table: cats
Create Table: CREATE TABLE `cats` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(150) NOT NULL,
  `gender` char(1) DEFAULT NULL,
  `owner` varchar(150) NOT NULL,
  `birth` date NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1
1 row in set (0.00 sec)
Use ALTER TABLE...DROP to delete a column:
mysql> ALTER TABLE cats DROP gender;
Query OK, 0 rows affected (0.19 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> DESCRIBE cats;
+-------+------------------+------+-----+---------+----------------+
| Field | Type             | Null | Key | Default | Extra          |
+-------+------------------+------+-----+---------+----------------+
| id    | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| name  | varchar(150)     | NO   |     | NULL    |                |
| owner | varchar(150)     | NO   |     | NULL    |                |
| birth | date             | NO   |     | NULL    |                |
+-------+------------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
See the Tutorial for more instructions on how to work with the MySQL server.

Other Important Tasks to Perform

Create more user accounts.  root is a superuser account for administration of the MySQL server which should not be used for general operations. On how to create user accounts of various kinds, see Adding User Accounts.
Configure MySQL to be managed with systemd.  If you have installed MySQL on a systemd platform using generic binaries and want it to be managed with systemd, seeManaging MySQL Server with systemd.

Troubleshooting

The following are resources for troubleshooting some problems you might run into:

Other Helpful Resources