Как удалить базу данных mysql через консоль
MySQL — самая популярная система управления реляционными базами данных с открытым исходным кодом.
В этом руководстве объясняется, как создавать базы данных MySQL или MariaDB через командную строку.
Подготовка
Мы предполагаем, что в вашей системе уже установлен сервер MySQL или MariaDB.
Все команды выполняются от имени администратора (минимальные права, необходимые для создания новой базы данных — CREATE ) или с учетной записью root.
Чтобы получить доступ к оболочке MySQL, введите следующую команду и при появлении запроса введите пароль root-пользователя MySQL:
Если вы не установили пароль для своего пользователя root MySQL, вы можете опустить опцию -p .
Если вам нужно изменить пароль root MySQL, следуйте этому руководству по сбросу пароля root MySQL с помощью командной строки.
Создать базу данных MySQL
Создать новую базу данных MySQL так же просто, как запустить одну команду.
Чтобы создать новую базу данных MySQL или MariaDB, выполните следующую команду, где database_name — это имя базы данных, которую вы хотите создать:
Чтобы избежать ошибок, если база данных с тем же именем, которое вы пытаетесь создать, существует, используйте оператор IF NOT EXISTS :
В выходных данных выше Query OK означает, что запрос был успешным, а одно 1 warning сообщает нам, что база данных уже существует, и что новая база данных не была создана.
Просмотреть все базы данных MySQL
Чтобы просмотреть базу данных, которую вы создали, из оболочки MySQL выполните следующую команду:
Приведенная выше команда распечатает список всех баз данных на сервере. Результат должен быть похож на этот:
Выберите базу данных MySQL
При создании базы данных новая база данных не выбирается для использования.
Чтобы выбрать базу данных перед началом сеанса MySQL, используйте следующую инструкцию:
После выбора базы данных все последующие операции, такие как создание таблиц, выполняются с выбранной базой данных.
Каждый раз, когда вы хотите работать с базой данных, вы должны выбирать ее с помощью оператора USE .
Вы также можете выбрать базу данных при подключении к серверу MySQL, добавив имя базы данных в конце команды:
Создайте базу данных MySQL с помощью mysqladmin
Вы также можете использовать утилиту mysqladmin для создания новой базы данных MySQL из терминала Linux.
Например, чтобы создать базу данных с именем database_name , вы должны использовать следующую команду:
Выводы
Мы показали вам, как создавать и выбирать базы данных MySQL с помощью оболочки MySQL и команды mysqladmin .
В данных примерах используется командная оболочка mysql и phpMyAdmin.
Если работа ведется на продуктивном сервере баз данных, рекомендуется сделать резервные копии.
Подключение к СУБД
Если мы планируем работать в командной строке, заходим в среду управления MySQL.
а) В Linux вводим команду:
* где root — пользователь, под которым мы будем подключаться к оболочке; ключ -p потребует ввода пароля.
б) В Windows запускаем командную строку — в меню пуск или найдя ее в поиске. Переходим в каталог, с установленной СУБД и запускаем одноименную команду mysql, например:
cd "%ProgramFiles%\MySQL\MySQL Server 5.5\bin\"
* в данном примере предполагается, что у нас установлена MySQL версии 5.5.
* здесь, как и в Linux, идет подключение к mysql/mariadb под учетной записью root с запросом пароля.
Создание новой базы
Для создания базы используется SQL-запрос CREATE DATABASE. Рассмотрим подробнее его использование.
Командная строка
Используйте данный шаблон команды:
> CREATE DATABASE newdb DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci;
* вышеописанная команда создаст базу данных с названием newdb и кодировкой UTF-8 (самая распространенная и универсальная).
Проверить, что база появилась можно командой:
* данная команда выводит в консоль список баз, созданных в СУБД.
Подключиться к базе можно командой:
phpMyAdmin
В phpMyAdmin переходим в раздел Базы данных - вводим название новой базы - выбираем кодировку и нажимаем Создать:
Настройка прав доступа
Чтобы к созданной базе можно было подключиться, добавим пользователя:
> GRANT ALL PRIVILEGES ON newdb.* TO dbuser@localhost IDENTIFIED BY 'password' WITH GRANT OPTION;
* где newdb.* — наша база и все ее таблицы; dbuser@localhost — имя учетной записи, которая будет подключаться с локального сервера; password — придуманный нами пароль.
** В данном примере, учетной записи будут предоставлены полные права (ALL PRIVILEGES). Подробнее о правах в MySQL читайте статью Как создать пользователя MySQL и дать ему права.
Посмотреть список пользователей, которые имеют доступ к базе можно командой:
> SELECT db, host, user FROM mysql.db WHERE db='newdb';
* в данном примере мы выведем учетные записи, которым был дан прямой доступ к созданной нами базе. В данном списке не будут отражены пользователи с глобальными правами (например, root).
Поменять пароль пользователю можно одной из команд (в зависимости от версии СУБД):
> SET PASSWORD FOR 'dbuser'@'localhost' = PASSWORD('new_password');
> ALTER USER 'dbuser'@'localhost' IDENTIFIED BY 'new_password';
* все 3 команды меняют пароль для пользователя dbuser@localhost на новый — new_password.
При необходимости, удалить пользователя можно командами:
> REVOKE ALL PRIVILEGES, GRANT OPTION FROM 'dbuser'@'localhost';
> DROP USER 'dbuser'@'localhost';
* первая команда отнимает все привилегии, выданные пользователю. Вторая удаляет самого пользователя.
mysql sends each SQL statement that you issue to the server to be executed. There is also a set of commands that mysql itself interprets. For a list of these commands, type help or \h at the mysql> prompt:
If mysql is invoked with the --binary-mode option, all mysql commands are disabled except charset and delimiter in noninteractive mode (for input piped to mysql or loaded using the source command).
Each command has both a long and short form. The long form is not case-sensitive; the short form is. The long form can be followed by an optional semicolon terminator, but the short form should not.
The use of short-form commands within multiple-line /* . */ comments is not supported. Short-form commands do work within single-line /*! . */ version comments, as do /*+ . */ optimizer-hint comments, which are stored in object definitions. If there is a concern that optimizer-hint comments may be stored in object definitions so that dump files when reloaded with mysql would result in execution of such commands, either invoke mysql with the --binary-mode option or use a reload client other than mysql .
Display a help message listing the available mysql commands.
If you provide an argument to the help command, mysql uses it as a search string to access server-side help from the contents of the MySQL Reference Manual. For more information, see Section 4.5.1.4, “mysql Client Server-Side Help”.
charset charset_name , \C charset_name
Change the default character set and issue a SET NAMES statement. This enables the character set to remain synchronized on the client and server if mysql is run with auto-reconnect enabled (which is not recommended), because the specified character set is used for reconnects.
Clear the current input. Use this if you change your mind about executing the statement that you are entering.
connect [ db_name [ host_name ]] , \r [ db_name [ host_name ]]
Reconnect to the server. The optional database name and host name arguments may be given to specify the default database or the host where the server is running. If omitted, the current values are used.
If the connect command specifies a host name argument, that host takes precedence over any --dns-srv-name option given at mysql startup to specify a DNS SRV record.
Change the string that mysql interprets as the separator between SQL statements. The default is the semicolon character ( ; ).
The delimiter string can be specified as an unquoted or quoted argument on the delimiter command line. Quoting can be done with either single quote ( ' ), double quote ( " ), or backtick ( ` ) characters. To include a quote within a quoted string, either quote the string with a different quote character or escape the quote with a backslash ( \ ) character. Backslash should be avoided outside of quoted strings because it is the escape character for MySQL. For an unquoted argument, the delimiter is read up to the first space or end of line. For a quoted argument, the delimiter is read up to the matching quote on the line.
mysql interprets instances of the delimiter string as a statement delimiter anywhere it occurs, except within quoted strings. Be careful about defining a delimiter that might occur within other words. For example, if you define the delimiter as X , it is not possible to use the word INDEX in statements. mysql interprets this as INDE followed by the delimiter X .
When the delimiter recognized by mysql is set to something other than the default of ; , instances of that character are sent to the server without interpretation. However, the server itself still interprets ; as a statement delimiter and processes statements accordingly. This behavior on the server side comes into play for multiple-statement execution (see Multiple Statement Execution Support), and for parsing the body of stored procedures and functions, triggers, and events (see Section 25.1, “Defining Stored Programs”).
Edit the current input statement. mysql checks the values of the EDITOR and VISUAL environment variables to determine which editor to use. The default editor is vi if neither variable is set.
The edit command works only in Unix.
Send the current statement to the server to be executed and display the result using vertical format.
Send the current statement to the server to be executed.
Disable output paging. See the description for pager .
The nopager command works only in Unix.
Disable output copying to the tee file. See the description for tee .
Disable display of warnings after each statement.
pager [ command ] , \P [ command ]
Enable output paging. By using the --pager option when you invoke mysql , it is possible to browse or search query results in interactive mode with Unix programs such as less , more , or any other similar program. If you specify no value for the option, mysql checks the value of the PAGER environment variable and sets the pager to that. Pager functionality works only in interactive mode.
Output paging can be enabled interactively with the pager command and disabled with nopager . The command takes an optional argument; if given, the paging program is set to that. With no argument, the pager is set to the pager that was set on the command line, or stdout if no pager was specified.
Output paging works only in Unix because it uses the popen() function, which does not exist on Windows. For Windows, the tee option can be used instead to save query output, although it is not as convenient as pager for browsing output in some situations.
Print the current input statement without executing it.
Reconfigure the mysql prompt to the given string. The special character sequences that can be used in the prompt are described later in this section.
If you specify the prompt command with no argument, mysql resets the prompt to the default of mysql> .
Define query attributes that apply to the next query sent to the server. For discussion of the purpose and use of query attributes, see Section 9.6, “Query Attributes”.
The query_attributes command follows these rules:
The format and quoting rules for attribute names and values are the same as for the delimiter command.
The command permits up to 32 attribute name/value pairs. Names and values may be up to 1024 characters long. If a name is given without a value, an error occurs.
If multiple query_attributes commands are issued prior to query execution, only the last command applies. After sending the query, mysql clears the attribute set.
If multiple attributes are defined with the same name, attempts to retrieve the attribute value have an undefined result.
An attribute defined with an empty name cannot be retrieved by name.
If a reconnect occurs while mysql executes the query, mysql restores the attributes after reconnecting so the query can be executed again with the same attributes.
Rebuild the completion hash that enables database, table, and column name completion while you are entering statements. (See the description for the --auto-rehash option.)
Reset the connection to clear the session state. This includes clearing any current query attributes defined using the query_attributes command.
Resetting a connection has effects similar to mysql_change_user() or an auto-reconnect except that the connection is not closed and reopened, and re-authentication is not done. See mysql_change_user(), and Automatic Reconnection Control.
This example shows how resetconnection clears a value maintained in the session state:
source file_name , \. file_name
Read the named file and executes the statements contained therein. On Windows, specify path name separators as / or \\ .
Quote characters are taken as part of the file name itself. For best results, the name should not include space characters.
Fetches, serializes, and optionally stores the session data of a successful connection. The optional file name and arguments may be given to specify the file to store serialized session data. If omitted, the session data is printed to stdout .
If the MySQL session is configured for reuse, session data from the file is deserialized and supplied to the connect command to reconnect. When the session is reused successfully, the status command contains a row showing SSL session reused: true while the client remains reconnected to the server.
Provide status information about the connection and the server you are using. If you are running with --safe-updates enabled, status also prints the values for the mysql variables that affect your queries.
system command , \! command
Execute the given command using your default command interpreter.
Prior to MySQL 8.0.19, the system command works only in Unix. As of 8.0.19, it also works on Windows.
tee [ file_name ] , \T [ file_name ]
By using the --tee option when you invoke mysql , you can log statements and their output. All the data displayed on the screen is appended into a given file. This can be very useful for debugging purposes also. mysql flushes results to the file after each statement, just before it prints its next prompt. Tee functionality works only in interactive mode.
You can enable this feature interactively with the tee command. Without a parameter, the previous file is used. The tee file can be disabled with the notee command. Executing tee again re-enables logging.
Use db_name as the default database.
Enable display of warnings after each statement (if there are any).
Here are a few tips about the pager command:
You can use it to write to a file and the results go only to the file:
You can also pass any options for the program that you want to use as your pager:
In the preceding example, note the -S option. You may find it very useful for browsing wide query results. Sometimes a very wide result set is difficult to read on the screen. The -S option to less can make the result set much more readable because you can scroll it horizontally using the left-arrow and right-arrow keys. You can also use -S interactively within less to switch the horizontal-browse mode on and off. For more information, read the less manual page:
The -F and -X options may be used with less to cause it to exit if output fits on one screen, which is convenient when no scrolling is necessary:
You can specify very complex pager commands for handling query output:
In this example, the command would send query results to two files in two different directories on two different file systems mounted on /dr1 and /dr2 , yet still display the results onscreen using less .
You can also combine the tee and pager functions. Have a tee file enabled and pager set to less , and you are able to browse the results using the less program and still have everything appended into a file the same time. The difference between the Unix tee used with the pager command and the mysql built-in tee command is that the built-in tee works even if you do not have the Unix tee available. The built-in tee also logs everything that is printed on the screen, whereas the Unix tee used with pager does not log quite that much. Additionally, tee file logging can be turned on and off interactively from within mysql . This is useful when you want to log some queries to a file, but not others.
The prompt command reconfigures the default mysql> prompt. The string for defining the prompt can contain the following special sequences.
Your full user_name @ host_name account name
x , for any “ x ” not listed above
You can set the prompt in several ways:
Use an environment variable. You can set the MYSQL_PS1 environment variable to a prompt string. For example:
Use a command-line option. You can set the --prompt option on the command line to mysql . For example:
Use an option file. You can set the prompt option in the [mysql] group of any MySQL option file, such as /etc/my.cnf or the .my.cnf file in your home directory. For example:
In this example, note that the backslashes are doubled. If you set the prompt using the prompt option in an option file, it is advisable to double the backslashes when using the special prompt options. There is some overlap in the set of permissible prompt options and the set of special escape sequences that are recognized in option files. (The rules for escape sequences in option files are listed in Section 4.2.2.2, “Using Option Files”.) The overlap may cause you problems if you use single backslashes. For example, \s is interpreted as a space rather than as the current seconds value. The following example shows how to define a prompt within an option file to include the current time in hh:mm:ss > format:
Set the prompt interactively. You can change your prompt interactively by using the prompt (or \R ) command. For example:
If the administrator creates your database for you when setting up your permissions, you can begin using it. Otherwise, you need to create it yourself:
Under Unix, database names are case-sensitive (unlike SQL keywords), so you must always refer to your database as menagerie , not as Menagerie , MENAGERIE , or some other variant. This is also true for table names. (Under Windows, this restriction does not apply, although you must refer to databases and tables using the same lettercase throughout a given query. However, for a variety of reasons, the recommended best practice is always to use the same lettercase that was used when the database was created.)
If you get an error such as ERROR 1044 (42000): Access denied for user 'micah'@'localhost' to database 'menagerie' when attempting to create a database, this means that your user account does not have the necessary privileges to do so. Discuss this with the administrator or see Section 6.2, “Access Control and Account Management”.
Creating a database does not select it for use; you must do that explicitly. To make menagerie the current database, use this statement:
Your database needs to be created only once, but you must select it for use each time you begin a mysql session. You can do this by issuing a USE statement as shown in the example. Alternatively, you can select the database on the command line when you invoke mysql . Just specify its name after any connection parameters that you might need to provide. For example:
menagerie in the command just shown is not your password. If you want to supply your password on the command line after the -p option, you must do so with no intervening space (for example, as -p password , not as -p password ). However, putting your password on the command line is not recommended, because doing so exposes it to snooping by other users logged in on your machine.
You can see at any time which database is currently selected using SELECT DATABASE() .
MySQL — самая популярная система управления реляционными базами данных с открытым исходным кодом.
В этом руководстве описывается, как удалить (или удалить) базу данных MySQL или MariaDB через командную строку.
Подготовка
Все команды выполняются с правами администратора (минимальные права, необходимые для удаления базы данных — DROP ) или с учетной записью root.
Чтобы получить доступ к консоли MySQL, введите следующую команду и при появлении запроса введите пароль root-пользователя MySQL:
Если вы не установили пароль для своего пользователя root в MySQL, вы можете опустить ключ -p .
Если вам нужно изменить пароль root MySQL, следуйте этому руководству по сбросу пароля root MySQL через командную строку.
Список всех баз данных MySQL
Перед тем как удалить базу данных, вы можете просмотреть список всех созданных вами баз данных . Для этого из оболочки MySQL выполните следующую команду:
Приведенная выше команда распечатает список всех баз данных на сервере. Результат должен быть похож на этот:
Удалить базу данных в MySQL
Удалить базу данных MySQL так же просто, как запустить одну команду. Это необратимое действие, и его следует выполнять с осторожностью. Убедитесь, что вы не удаляете неправильную базу данных, поскольку после удаления базы данных ее невозможно будет восстановить.
Перед выполнением запроса на перетаскивание всегда рекомендуется создать резервную копию базы данных .
Чтобы удалить базу данных, введите следующую команду, где database_name — это имя базы данных, которую вы хотите удалить:
Чтобы не видеть ошибок, как указано выше, используйте вместо этого следующую команду:
В выходных данных выше Query OK означает, что запрос был успешным, а одно 1 warning сообщает нам, что база данных не существует и никакая база данных не была удалена.
Удалить базу данных MySQL с помощью mysqladmin
Вы также можете удалить базу данных MySQL из терминала Linux с помощью утилиты mysqladmin .
Например, чтобы удалить базу данных с именем database_name , введите следующую команду и введите пароль корневого пользователя MySQL при появлении запроса:
Читайте также: