Перейти к содержимому

Mysql как войти в пользователя

  • автор:

Управление пользователями MySQL или MariaDB через командную строку

Управление пользователями MySQL или MariaDB через командную строку

Командная строка MySQL — основной инструмент для работы с MySQL, который присутствует в любой версии данной СУБД, под любую платформу. В этой статье мы разберем управление пользователями данной системы управления базами данных.

Авторизация через командный интерфейс MySQL

Так как MariaDB является форком MySQL, то утилита управления сервером тоже называется mysql. Для входа под суперпользователем, в терминале нужно выполнить команду и ввести его пароль:

Или под любым другим пользователем, который имеет доступ к управлению пользователями:

Создание пользователя

Для создания пользователя понадобится выполнить одну единственную команду:

Конечно же, значения [ИМЯ ПОЛЬЗОВАТЕЛЯ] и [ПАРОЛЬ ПОЛЬЗОВАТЕЛЯ] нужно заменить на свои.

Проверить, появился ли новый пользователь, можно с помощью команды, которая отобразит всех пользователей на данном сервере MySQL:

После выполнения данной команды, будет создан пользователь.

Выдача пользователю прав доступа

Поскольку свежесозданный пользователь не будет иметь никаких прав, то работать с базами данных он не сможет. Для работы с какой-то определенной базой, ему нужно дать на неё права.

Выдать права доступа «только для чтения» (пользователь сможет только просматривать данные, но не редактировать их) на определенную базу данных можно следующей командой:

Выдать полные права (пользователь сможет редактировать данные) доступа на определенную базу данных можно следующей командой:

Посмотреть права пользователя можно с помощью команды SHOW GRANTS:

Удаление пользователя

Удаляется пользователь с помощью следующей команды:

Для того, чтобы убедиться, что нужный пользователь был удален, достаточно выполнить простую команду:

И посмотреть в выводе командной строки, присутствует ли пользователь, которого Вы удаляли, или нет.

How to manage users and authentication in MySQL

User management is of the most important responsibilities of anyone hoping to manage a MySQL database system. Creating, altering, and deleting user accounts to best represent the users and services in your environment helps lay the groundwork for locking down access, limiting scope for changes, and implementing auditing and accountability for modifications.

In this guide, we will talk about how to manage user accounts within MySQL. First, we will discuss what a valid user is in MySQL and show you how to add additional users to the system. This leads into a discussion about how to configure authentication for each user and how the system chooses an authentication option from a list of possibilities. We'll continue on to talk about making changes to existing users, how to log in with the accounts you've created, and how to delete users you no longer need.

To follow along with this guide, you'll need an account on a MySQL server with the appropriate privileges.

Commands we will use

To create, modify, and delete users within MySQL, the core commands you need are:

  • CREATE USER : create a new user account
  • ALTER USER : make changes to an existing user account
  • DROP USER : remove an existing user account

To execute the commands above, you need to login to MySQL with an account with CREATE USER privileges. The CREATE USER privilege allows you to create, modify, delete, and rename users, among other actions. We'll also need the SELECT privilege on the mysql database to see information about existing users.

In order of preference, you should login using:

  • A limited account that has the CREATE USER privilege and the SELECT privilege on the mysql database
  • The root or administrative user that has full privileges within MySQL

Understanding how MySQL defines and interprets user accounts

Before we start creating new accounts, it's helpful to take some time to get familiar with the various that MySQL uses for creating and referring to users. You also need to be familiar with MySQL's authentication algorithm to understand what user account it will use to authenticate connections.

What is MySQL's syntax for user accounts?

In MySQL, user accounts are composed of two separate pieces of information, joined by an at sign (@):

  • The user name
  • The host that the user is connecting from

In general, user accounts on the system will look like the following:

Single quotes can be used, as above, to individually wrap the user and host components of the user account. They are sometimes necessary if either of the components contain characters that would otherwise be misinterpreted. In general, adding them is always a good idea to be explicit.

So rather than just having an account called 'john' , in MySQL, the full account name would require some kind of host, such as 'john'@'localhost' . This means that there may be multiple 'john' accounts on the system and MySQL will view each of them as a unique account as long as they are coming from a different domain.

With all this being said, it's possible to define user accounts that do not have a user or host component, but there are important implications that you must be aware of.

You can define a user account without a user value by using an empty string:

For instance, you could create a user as ''@'localhost' . This user would match any username connecting from the local computer.

Likewise, you could have a user account that matches from any host. Rather than using an empty string, for host values, you would use the % wildcard, like this:

For example, if you create 'john'@'%' , that account would match a 'john' user connecting from any host.

How does MySQL authenticate users?

Understanding how MySQL actually processes each authentication request is very important to avoid a common class of authentication problems that result from reasonable, but incorrect assumptions. This was discussed in some depth in our introduction to authentication and authorization in MySQL article.

When authenticating a connection request, MySQL uses a number of fields within the user table of its internal mysql database to decide whether to allow the connection. MySQL will use at most one user account record to try to authenticate a connection. This means that MySQL needs a way to decide on which user account to use if there are more than one accounts that could match a connection.

MySQL's algorithm for authenticating users begins when the server starts up. On start up, MySQL loads the entire mysql.user table into memory. It also does this whenever user accounts are created using the regular MySQL commands. As it loads the table, it sorts the entries from highest priority to lowest.

MySQL uses the Host column as the primary sort field and prioritizes results with more specific values. So literal values are sorted to the top as the highest priority and those that use wildcards, like % , are sorted to the bottom. The final entries are those that only contain % with no other characters, followed by entries that have a completely blank host.

The User column is used as a secondary sort field for any entries that have the same Host value. Once again, the more exact matches are prioritized. Since the User column cannot use wildcards, all entries are at equal footing except for those with a blank User value. Those are sorted to the bottom. If any entry with a blank User value is selected, the user will be authenticated as an "anonymous user", which usually equates to having no privileges.

Now, whenever a connection request is made, MySQL goes through its sorted table in memory from the top to the bottom. It uses the first entry it finds to authenticate the user, regardless if there are other entries that would also match. If the client fails to authenticate using the method defined by that entry, the connection will fail and no other entries will be checked.

What are the implications of not including a user or host in a MySQL user account definition?

Because of MySQL's authentication algorithm, problems can emerge if you're not careful when creating user accounts without a user or host component. This is because the way that MySQL decides which record to use to authenticate you can be unintuitive and surprising.

For instance, if a user authenticates to MySQL with the user portion as a blank string, MySQL will consider them an "anonymous user" for the remainder of the session. As a rule, anonymous users have almost no power and can do very little once connected. It's possible to even accidentally authenticate as an anonymous user when trying to authenticate using a different user account.

The challenge with using wildcard hosts for user accounts is that other user accounts that include a host value can easily mask, or make unavailable, the user account that uses the wildcard.

For instance, if you have a user account defined as 'emily'@'%' , you might expect to be able to authenticate to 'emily' from any host. However, if you have a user account with a blank user but a host value that matches the host 'emily' is connecting from, MySQL will authenticate using that account instead (leading to an anonymous user login as described above).

So as an example, MySQL will sort the following accounts into the following order:

Priority MySQL account Comments
1 'emily'@'localhost' and 'emily'@'example.com' These are of equal priority, which is okay because it's only possible for one of them to match a connection.
2 ''@'localhost' and ''@'example.com' These two entries are, again of the same priority. Since they don't have a user component, but they do have a literal host component, they are placed at the bottom of the entries that have exact host values.
3 'emily'@'%.example.com' This entry has a wildcard in the host component, so it's given lower priority than entries with exact host values.
4 ''@'%.example.com' This entry is grouped with the entries that have a wildcard within their host value. Since it has no user component, it is at the bottom of this group.
5 'emily'@'%' This entry has a host value consisting only of a wildcard. Since it matches any host, it has a very low priority.
7 ''@'%' This entry can be used authenticate any user from any host as an anonymous user. It's of extremely low priority since it matches any connection.
6 'emily'@'' This entry has an entirely blank host value, which is of even lower priority than a host that only contains a wildcard host.
8 ''@'' This is the lowest possible priority user. It contains no host information so it is place at the end during the host sorting. Since it also contains a blank user, it is placed below other entries in this group. Like all entries without a user, connections authenticated with this entry will be signed in as an anonymous user.

How do you create users?

Now that you have a feel for the way that MySQL handles user accounts, we can begin creating some new users. Remember to login with a user with the privileges described in the prerequisites.

The basic syntax for creating a new user is relatively simple. You use the CREATE USER command and then specify the user and host for the new account:

This will create a basic account without configuring any details beyond its user and host at creation.

How do you create a user with a password?

Often, you want to configure authentication while you're creating the user. You can do this by adding the optional IDENTIFIED BY clause onto CREATE USER statement:

This creates a new user account, as before, and assigns a password for the account at the same time. We will cover how to assign a password after the fact or how to change a user's password later on.

How do you create a user with Unix socket authentication?

While password authentication is the most common authentication method for most users, it's not the only option. MySQL provides many different internal and external authentication mechanisms that you can configure to your user accounts to use. As an example, we'll configure a new account using Unix socket authentication.

Unix socket authentication can be used in Linux or Unix-like environments so that an account on the operating system is given access to the same account name within MySQL without further authentication. In this configuration, the MySQL administrator knows that user accounts on the operating system are tightly controlled.

So if there is a mary user on the operating system, they will be able to login to the 'mary'@'localhost' account within MySQL if Unix socket authentication is the defined authentication mechanism. Let's configure this now.

Socket authentication requires the auth_socket plugin, so first load the plugin by typing:

Next, create a user account that matches a user account you have on your operating system. For this example, we'll use the mary account we discussed above. If you don't use a name that matches one of your operating system names, you won't be able to authenticate using this user.

To create the user with socket authentication, we need to use the IDENTIFIED WITH clause (different than the IDENTIFIED BY clause used earlier) to specify the authentication plugin to use:

Now, you should be able to authenticate to the 'mary'@'localhost' MySQL user from the mary user on your operating system. When logged in as mary , connect to the database without providing any username or password:

You should be signed in automatically through the Unix socket authentication you configured.

How do you show existing users?

Next, let's take a look at how to find information about the existing users.

To show all of the existing MySQL users, consisting of their user and host component, as well as the authentication plugin they're currently using, you can SELECT those fields from the mysql.user database:

Here, we can see that there are six users defined on the system, all of which can only login locally. Five of the accounts are configured to use password authentication. The 'mary'@'localhost' account is configured to use Unix socket authentication.

We can find additional information about user properties by using the SHOW CREATE USER command. In spite of its name, it shows all of the current properties of a user account, not necessarily the ones that were used during the initial account creation.

The SHOW CREATE USER command takes an account name as an argument:

It's usually best to end the command with the \G statement terminator instead of the usual colon ( ; ) so that you can view the results a bit more clearly.

To display the properties for the 'useradmin'@'localhost' account, you would type:

How do you change existing MySQL users?

You can change existing users within MySQL using the ALTER USER command. This can be used to change most of the user-related properties of an account, with the exception of account privileges, which are controlled by the GRANT and REVOKE commands.

The basic syntax for ALTER USER looks like this:

How do you change the password for a MySQL user?

For most people, the most common use of ALTER USER is to modify passwords.

For example, you can modify the password for 'kamal'@'localhost' by typing:

If you want to set a temporary password for a user that they'll have to replace immediately, you can set and expire a password at the same time:

You can always change your own password, even without the CREATE USER privilege. It's easiest to use the USER() function to automatically fill in your own username:

How do you change authentication plugins for a MySQL user?

You can also change the mechanism or plugin used to authenticate an account.

In an earlier example, we configured an account called 'mary'@'localhost' to use Unix socket authentication. If we later want to change that account to use conventional password authentication, we can use the ALTER USER command again.

First, identify the default authentication plugin for your server. If it's a password-based authentication method, it's probably best to reuse the default selection:

In this case, the default authentication plugin is caching_sha2_password , so we'll use that when we switch to password authentication.

Now, change 'mary'@'localhost' to use the caching_sha2_password plugin with a new password:

The 'mary'@'localhost' user will no longer be able to login using Unix socket authentication, but they can log in using the provided password.

How do you login to MySQL?

We've discussed how to create and modify MySQL user accounts, including authentication. However, we haven't talked about how to actually login using these authentication methods.

The mysql client is a powerful command line client that can be used to connect to local and remote databases. We'll use it to talk about how to authenticate using the methods we configured above.

How do you login to a local database with a password?

To login to a locally hosted MySQL database using a user account with a password, the basic syntax looks like this:

So, if the 'kamal'@'localhost' user wants to login to MySQL and connect to the testing database from the computer where the system is hosted, they can type:

The mysql client will prompt for the password for 'kamal'@'localhost' . If you provide the correct credentials, you'll be connected to the testing database.

Specifying a database on the command line is optional. If none is specified, you'll connect to the server but not to a specific database.

How do you login to a local database with Unix socket authentication?

To login to a local MySQL server using Unix socket authentication, you need to be logged into your operating system as the account name that matches. So, if we want to authenticate to 'mary'@'localhost' using Unix socket authentication, we first have to login to our computer with a username called mary .

Once you are using the correct operating system account, you can connect directly to the local database by executing the client, with no options.

As before, you can optionally append a database name to connect to a specific database you'd like.

How do you login to a remote database with a password?

If your MySQL server isn't running on your local server, you'll have to specify the host that the client should try to connect to. You can do that by adding the —host option.

Most of the time, you'll be authenticating with a password to remote MySQL servers, so the command would look something like this:

So 'tanya'@'<tanyas_domain>' could connect to a MySQL server located on example.com by typing:

How do you delete MySQL users?

Keeping user accounts around that no longer serve a purpose is a security risk. You can remove accounts easily with the DROP USER command.

The basic syntax looks like this:

So to delete the 'mary'@'localhost' user, you would type:

If you try to delete a user that does not exist, you will receive an error:

To avoid this, you can add the IF EXISTS clause before the account name. If the user exists, it will be deleted. If it does not, only a warning will be given:

MySQL's user account management and authentication configuration is highly flexible. Learning how to create, modify, and get information about users within MySQL will help you administer your database systems more effectively.

Security best practices dictate that you should create accounts for each unique use case, given only the level of access required to perform their scope. Account creation and authentication are the first stages of this process. In another guide, we'll talk about granting and revoking privileges to fulfill the other part of that strategy.

How do you change user passwords in MySQL?

The most common way to change a user's password is to use ALTER USER . For example you can modify the password for 'kamal'@'localhost' by using:

You can also set a temporary password by using:

How do I fix root user access errors in MySQL?

There are several potential reasons that you might receive an error when trying to login as a root user to a MySQL database. MySQL addresses the troubleshooting checks that you can do in their documenation.

Some common cases include needing to reset the root user password or editing the configuration file.

How do you drop users in MySQL?

You can drop users in MySQL by using the DROP USER command. The basic syntax looks like this:

To avoid attempting to drop a user that does not exist, you can include the IF EXISTS clause before the account name.

Вводная

Есть несколько вариантов установки, в зависимости от того, будете ли вы использовать СУБД на своём личном компьютере (что рекомендуется для полноценного освоения), или будете использовать компьютеры института.

Установка на личном компьютере

Вы можете воспользоваться тем же вариантом, что и для установки на компьютер института, но проще будет использовать специальный инсталлятор. Для установки на личном компьютере вы просто скачиваете с сайта http://dev.mysql.com/downloads/mysql/ MySQL installer — это стандартный установщик, при помощи которого вы установите MySQL так же, как любую другую прогрумму Windows. В процессе установке следует выбрать вариант «Developer Default», чтобы установить полный необходимый вам набор инстурментов. Все остальные параметры можно оставить по умолчанию. Пароль для администратора вы можете придумать сами.

Установка на компьютере института

Скачать актуальный дистрибутив СУБД MySQL можно по адресу
https://dev.mysql.com/downloads/mysql/
Нам понадобится вариант Windows (x86, 64-bit), ZIP Archive. Скорее всего, вы так же можете получить его из сетевого диска, куда его предварительно скопировал преподаватель. В данном случае вы просто распаковываете скачанный архив к себе на локальный (не сетевой!) диск.

Запуск MySQL

Запуск на личном компьютере

В случае, если вы установили MySQL при помощи инсталлятора, то его запуск и остановка будут осуществляться через управление службами Windows. По умолчанию после установки сервис должен уже работать.

Запуск на компьютере института

Управление сервером будет осуществляться из командной строки. Для этого необходимо выполнить следующие команды (перейдя в папку MySQL):

  1. Сначала инициализируем базу:
  2. Запомните пароль, который будет сгенерирован для пользователя root
  3. Теперь запускаем базу: Если вы всё проделали правильно, то в консоли должна появиться строка «mysqld.exe: ready for connections».
    После этого консоль перестаёт принимать ваш ввод и работает только на вывод информации. Не закрывайте эту консоль — вместе с ней вы закроете серверный процесс и больше не сможете общаться с СУБД! Для того, чтобы работать дальше, вам потребуется открыть ещё одну консоль.
  4. И меняем пароль. Для этого запускаем клиентскую программу mysql и вводим текущий пароль.
  5. И, оказавшись в консоли MySQL, меняем пароль: Не забудьте переподключиться и проверить, что пароль поменялся! Выйти из консоли MySQL в консоль Windows можно командой

Привилегии в MySQL

Для работы с базами данных в MySQL необходим пользователь, наделённый такими правами. То есть при подключении к базе данных Вы должны указывать логин пользователя и его пароль, и если доступ ему открыт, то он получит определённые права.

В MySQL существуют три группы привилегий: данные, структура, администрирование. Первая группа связана с изменением записей в таблицах, вторая группа связана с изменением структуры баз данных, а третья связана с администрированием, как бы это очевидно не звучало.

Теперь перейдём к рассмотрению каждой группы отдельно. И начнём с прав на управление данными в таблицах.

  • SELECT — эта привилегия позволяет делать выборку (вытаскивание) записей из таблиц баз данных.
  • INSERT — привилегия, которая необходима для добавления новых записей в таблицу.
  • UPDATE — право, позволяющее обновлять записи в таблице.
  • DELETE — эта привилегия позволяет удалять записи из таблицы.
  • FILE — разрешает делать выборку записей и записывать данные в файл, а также считывать их оттуда.

Теперь перейдём к привилегиям пользователей MySQL, позволяющие изменять структуру таблицы и базы данных.

  • CREATE — привилегия, позволяющая создавать новые базы данных, а также новые таблицы в базе данных.
  • ALTER — привилегия, позволяющая переименовывать таблицы, вставлять новые поля в таблицу, удалять поля из таблицы, а также модифицировать их.
  • INDEX — разрешает создавать индекс по определённому полю и удалять его. О том, что это такое и для чего нужно мы поговорим в одной из следующих статей.
  • DROP — право, которое позволяет удалять либо таблицы, либо целые базы данных.
  • CREATE TEMPORARY TABLES — возможность создавать временные таблицы, которые хранятся во время сессии, а после окончания сессии данная таблица автоматически удаляется.

И последняя группа привилегий — это привилегии, связанные с администрированием баз данных.

  • GRANT — привилегия, которая позволяет создавать новых пользователей, а также менять права у существующих. Тут есть очень важная деталь: нельзя изменять значения привилегий, которыми сам не обладаешь. То есть если человек обладает привилегией GRANT, но не обладает привилегией SELECT, то он не может новым пользователям дать привилегию SELECT. Впрочем, это вполне логично.
  • SUPER — позволяет использовать команду «kill«, то есть убить поток. Поток — это текущее подключение другого пользователя к базе данных.
  • PROCESS — привилегия, позволяющая выполнить команду «processlist«, которая показывает список потоков.
  • RELOAD — позволяет открывать и закрывать файлы журналов, а также перечитывать таблицы привилегий пользователей.
  • SHUTDOWN — привилегия, позволяющая выполнить команду «shutdown«, отключающая работу сервера.
  • SHOW DATABASES — разрешает просматривать все существующие базы данных.
  • REFERENCES — данная привилегия ещё не доступна, а только зарезервирована для использования в будущем.
  • LOCK TABLES — позволяет блокировать таблицы от указанных потоков.
  • EXECUTE — позволяет запускать хранимые процедуры.
  • REPLICATION CLIENT — даёт право получать местонахождение ведущего (master) и ведомых (slaves) серверов.
  • REPLICATION SLAVE — это привилегия, позволяющая читать ведомым журнала ведущего сервера.

И, наконец, специальные привилегии, связанные с ограничением на доступные ресурсы:

  • MAX QUERIES PER HOUR — максимальное количество запросов в час, которое может отправить пользователь.
  • MAX UPDATES PER HOUR — максимальное количество команд в час, которые каким-либо образом изменяют либо таблицу, либо базу данных.
  • MAX CONNECTIONS PER HOUR — максимальное количество подключений в час, которое может сделать пользователь.

Если значение вышеназванных пределов равны «0«, то ресурсы для пользователя не ограничены.

Создание нового пользователя в MySQL

Ранее мы вносили все изменения в настройки MySQL под root-пользователем, имея полный доступ ко всем базам данных. Однако для случаев, когда могут потребоваться более жесткие ограничения, есть способы создания пользователей с особыми наборами прав доступа.

Давайте начнем с создания нового пользователя из консоли MySQL:

К сожалению, на данном этапе пользователь «newuser» не имеет прав делать что-либо с базами данных. На самом деле, даже если если пользователь «newuser» попробует залогиниться (с паролем «password»), он не попадет в консоль MySQL.

Таким образом, первое, что нам необходимо сделать, это предоставить пользователю доступ к информации, которая ему потребуется.

Звездочки в этой команде задают базу и таблицу, соответственно, к которым у пользователя будет доступ. Конкретно эта команда позволяет пользователю читать, редактировать, выполнять любые действия над всеми базами данных и таблицами.

Поле завершения настройки прав доступа новых пользователей, убедитесь, что вы обновили все права доступа:

Теперь ваши изменения вступят в силу.

Назначение привилегий

Для назначения прав конкретному пользователю можно использовать следующую схему:

Если вы хотите дать доступ к любой базе данных или к любой таблице, поставьте звездочку (*) вместо названия базы данных или таблицы.

Каждый раз, когда вы изменяете права доступа, не забудьте использовать команду Flush Privileges.

Лишения прав доступа практически идентично их назначению:

По аналогии с использованием команды DROP для удаления базы данных, вы можете использовать эту команду и для удаления пользователя.

Для тестирования учетной записи созданного пользователя, разлогиньтесь с помощью команды:

и залогиньтесь снова, введя в терминате следующую команду:

Основные утилиты MySQL.

В состав дистрибутива MySQL входят следующие утилиты:

  • mysqld
  • mysql
  • mysqladmin
  • mysqlaccess
  • mysqlshow
  • mysqldump
  • isamchk

Утилиты mysqld и mysql были подробно рассмотрены ранее, поэтому возвращаться к ним не будем. Кратко рассмотрим остальные.

Mysqladmin

Утилита для администрирования сервера. Может использоваться администратором, а также некоторыми пользователями, которым предоставлены определенные привилегии, например – Reload_priv, Shutdown_priv, Process_priv и File_priv. Данная команда может использоваться для создания баз данных, изменения пароля пользователя(администратор может изменить пароль любому пользователю, а рядовой пользователь – только свой собственный), перезагрузки и остановки сервера, просмотра списка процессов, запущенных на сервере. Mysqladmin поддерживает следующие команды:

  • Create [database_name] Создает базу данных
  • Drop [database_name] Удаляет базу данных и все таблицы в ней
  • Reload Перезагружает сервер
  • Shutdown Останавливает работу сервера MySQL
  • Processlist Выводит список процессов на сервере
  • Status Выводит сообщение о статусе сервера

Пример использования mysqladmin для изменения пароля:

Следует заметить, что в случае использования mysqladmin для установки пароля, не требуется использование функции password().Mysqladmin сам заботится о шифровании пароля.

Mysqlaccess

  • -?, —help Справка
  • -u, —user=[username] Имя пользователя
  • -p, —password=[password] Пароль пользователя
  • -h, —host=[hostname] Имя хоста для проверки прав доступа
  • -d, —db=[dbname] Имя базы данных для проверки прав доступа
  • -U, —superuser=[susername] Имя суперпользователя(root)
  • -P, —spassword=[spassword] Пароль администратора
  • -b, —brief Выводит краткие сведения о таблице

Mysqlshow

  • -?, —help Справка
  • -h, —host=[hostname] Имя сервера
  • -k, —key Показать ключи для таблицы
  • -p, —password=[password] Пароль пользователя
  • -u, —user=[username] Имя пользователя
  • -p, —port=[port] Порт для связи
  • -V, —version Вывести информацию о версии

Mysqldump

  • -#, —debug=[options] Вывести в протокол отладочную информацию. В общем виде ‘d:t:o, filename`.
  • -?, —help Справка.
  • -c, —compleat-insert Генерируйте полные инструкции insert (не исключая значений, которые соответствуют значениям столбца по умолчанию).
  • -h, —host=[hostname] Соединиться с сервером hostname.
  • -d, —no-data Экспорт только схемы информации (исключая данные).
  • -t, —no-create-info Экспорт только данных, исключая информацию для создания таблицы. Противоположность -d.
  • -p, —password=[password] Пароль пользователя, для соединения с сервером MySQL. Обратите внимание, что не должно быть пробела между -p и паролем.
  • -q, —quick Не буферизовать результаты запроса, дамп выдать непосредственно к STDOUT.
  • -u, —user=[username] Имя пользователя. Если не задано, используется текущий логин.
  • -v, —verbose Вывести подробную информацию относительно различных стадий выполнения mysqldump.
  • -P, —port=[port] Порт для связи.
  • -V, —version Информация о версии.

Вы можете направить вывод mysqldump в клиентскую программу MySQL, чтобы копировать базу данных. ПРИМЕЧАНИЕ: Вы должны убедиться, что база данных не изменяется в это время, иначе Вы получите противоречивую копию!

Примечание флаг –p используется в случае, если пользователь наделен паролем.
После выполнения этой команды появился файл mysql-1.sql и mysql-2.sql. Загрузите их в текстовый редактор, чтобы поподробнее изучить.

How to switch users on MySQL

what is the windows command to switch to users on MySQL Im having a little problem in using mysql on windows. I know how to create a new user and giving grants to the new user and all. But i don’t know how to switch to new user from mysql console!

macavity's user avatar

5 Answers 5

I figured out solution. There is system command, where we can execute shell command like ‘ls, cd, mv, mkdir etc.. Here we can login as different user. first I logged in as regular user.

Now user got changed to madegow user. but when you run quit/exit it will not go back to root. we need to bare with that.

I was looking for an equivalence of the CONNECT command of Oracle Database and just found it with the command \CONNECT available on MySQL Shell (since version 5.7.12), but that’s another story.

So, as said years ago by our friend Shivakumara, the answer is:

Which is nothing but calling an OS shell command from MySQL prompt.

The MySQL CLI session is bound to the user which started it. Thus, you’ll have to open a new session with the desired user after you’ve created it and set needed grants. You can open a new session and keep the current one. Or, you can end the current session and then start new a one:

where USER is name of new user and DATABASE is database to switch to when you log on ( -p points that you’ll prompted to enter password). To exit the session, just use exit .

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Капельница от запоя — облегчение за 15–20 минут