Friday, January 17, 2020

How to Create MySQL Users Accounts and Grant Privileges

MySQL is the most popular open-source relational database management system. MySQL server allows us to create numerous user accounts and grant appropriate privileges so that users can access and manage databases.
This tutorial describes how to create MySQL user accounts and grant privileges.

Before you Begin

We are assuming that you already have MySQL or MariaDB server installed on your system.
All commands are executed inside the MySQL shell as root or administrative user. The minimum privileges required to create user accounts and define their privileges is CREATE USER and GRANT.
To access the MySQL shell type the following command and enter your MySQL root user password when prompted:

mysql -u root -p
If you haven't set a password for your MySQL root user, you can omit the -p switch.

Create a new MySQL User Account

A user account in MySQL consists of a user name and host name parts.

To create a new MySQL user account, run the following command:
CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'user_password';
Replace the placeholder value newuser with your intended new user name, and placeholder value user_password with the user password.
In the command above the hostname part is set to localhost, which means that the user will be able to connect to the MySQL server only from the localhost (i.e from the system where MySQL Server runs).
To grant access from another host, change the hostname part (localhost) with the remote machine IP. For example, to grant access from a machine with IP 10.8.0.5 you would run:
CREATE USER 'newuser'@'10.8.0.5' IDENTIFIED BY 'user_password';
To create a user that can connect from any host, use the '%' wildcard as a host part:
CREATE USER 'newuser'@'%' IDENTIFIED BY 'user_password';

Grant Privileges to a MySQL User Account

There are multiple types of privileges that can be granted to a user account. You can find a full list of privileges supported by MySQL here.

The most commonly used privileges are:
  • ALL PRIVILEGES – Grants all privileges to a user account.
  • CREATE – The user account is allowed to create databases and tables.
  • DROP - The user account is allowed to drop databases and tables.
  • DELETE - The user account is allowed to delete rows from a specific table.
  • INSERT - The user account is allowed to insert rows into a specific table.
  • SELECT – The user account is allowed to read a database.
  • UPDATE - The user account is allowed to update table rows.
To grant specific privileges to a user account, you can use the following syntax:
GRANT permission1, permission2 ON database_name.table_name TO 'database_user'@'localhost';
Here are some examples:
  • Grand all privileges to a user account over a specific database:
    GRANT ALL PRIVILEGES ON database_name.* TO 'database_user'@'localhost';
  • Grand all privileges to a user account on all databases:
    GRANT ALL PRIVILEGES ON *.* TO 'database_user'@'localhost';
  • Grand all privileges to a user account over a specific table from a database:
    GRANT ALL PRIVILEGES ON database_name.table_name TO 'database_user'@'localhost';
  • Grant multiple privileges to a user account over a specific database:
    GRANT SELECT, INSERT, DELETE ON database_name.* TO database_user@'localhost';

Display MySQL User Account Privileges

To find the privilege(s) granted to a specific MySQL user account, use the SHOW GRANTS statement:

SHOW GRANTS FOR 'database_user'@'localhost';
+---------------------------------------------------------------------------+
| Grants for database_user@localhost                                       |
+---------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'database_user'@'localhost'                        |
| GRANT ALL PRIVILEGES ON `database_name`.* TO 'database_user'@'localhost' |
+---------------------------------------------------------------------------+
2 rows in set (0.00 sec)

Revoke Privileges from a MySQL User Account

The syntax to revoke one or more privileges from a user account is almost identical as when granting privileges.
For example, to revoke all privileges from a user account over a specific database, use the following command:
REVOKE ALL PRIVILEGES ON database_name.* FROM 'database_user'@'localhost';

Remove an Existing MySQL User Account

To delete a MySQL user account use the DROP USER statement:
DROP USER 'user'@'localhost'
The command above will remove the user account and its privileges.

Conclusion 

This tutorial covers only the basics, but it should be a good starting for anyone who wants to learn how to create new MySQL user accounts and grant privileges.
If you have any questions or feedback, feel free to leave a comment.

Tuesday, December 17, 2019

How to convert an entire MySQL database characterset and collation to UTF-8?

Use the ALTER DATABASE and ALTER TABLE commands.
ALTER DATABASE databasename CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
ALTER TABLE tablename CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
Or if you're still on MySQL 5.5.2 or older which didn't support 4-byte UTF-8, use utf8 instead of utf8mb4:
ALTER DATABASE databasename CHARACTER SET utf8 COLLATE utf8_unicode_ci;
ALTER TABLE tablename CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;

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