Linux mysql create database

ИТ База знаний

Курс по Asterisk

Полезно

— Узнать IP — адрес компьютера в интернете

— Онлайн генератор устойчивых паролей

— Онлайн калькулятор подсетей

— Калькулятор инсталляции IP — АТС Asterisk

— Руководство администратора FreePBX на русском языке

— Руководство администратора Cisco UCM/CME на русском языке

— Руководство администратора по Linux/Unix

Серверные решения

Телефония

FreePBX и Asterisk

Настройка программных телефонов

Корпоративные сети

Протоколы и стандарты

Как создавать и выбирать базы данных MySQL в Linux

All your base are belong to us

3 минуты чтения

MySQL — одна из самых популярных систеа управления реляционными базами данных с открытым исходным кодом. В этом руководстве объясняется, как создавать базы данных MySQL или MariaDB с помощью командной строки Linux.

Мини — курс по виртуализации

Знакомство с VMware vSphere 7 и технологией виртуализации в авторском мини — курсе от Михаила Якобсена

Подготовка

У вас в системе должен быть установлен сервер MySQL или MariaDB.

Все команды выполняются от имени администратора (минимальная привилегия, необходимая для создания новой базы данных — CREATE ) или с учетной записью root.

Чтобы получить доступ к оболочке MySQL, используйте команду:

После чего чего появится запрос где нужно ввести пароль пользователя root MySQL. Если вы не установили пароль для своего рутового пользователя MySQL, вы можете пропустить опцию -p .

Создание базы данных MySQL

Создать новую базу данных MySQL так же просто, как запустить одну команду.

Чтобы создать новую базу данных MySQL или MariaDB, введите следующую команду, где database_name — это имя базы данных, которую вы хотите создать:

Мы должны получить следующий вывод:

Если вы попытаетесь создать базу данных, которая уже существует, вы увидите следующее сообщение об ошибке:

Чтобы избежать ошибок, если база данных с тем же именем, которое вы пытаетесь создать, существует, используйте оператор IF NOT EXISTS :

Получим следующий вывод:

В приведенном выше выводе Query OK означает, что запрос был успешным, а 1 предупреждение говорит нам, что база данных уже существует, и новая база данных не была создана. Учитывайте что в Linux базы данных MySQL и имена таблиц чувствительны к регистру.

Просмотреть все базы данных MySQL

Чтобы просмотреть созданную вами базу данных из оболочки MySQL, выполните следующую команду:

Команда выше выведет список всех баз данных на сервере. Вывод должен быть похож на это:

Выбрать базу данных MySQL

При создании базы данных, новая база данных не выбирается для использования.

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

Получим такой вывод:

После выбора базы данных все последующие операции, такие как создание таблиц, выполняются с выбранной базой данных.

Каждый раз, когда вы хотите работать с базой данных, вы должны выбрать ее с помощью оператора USE .

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

Создание базы данных MySQL с помощью mysqladmin

Вы также можете использовать утилиту mysqladmin для создания новой базы данных MySQL из терминала Linux.

Например, чтобы создать базу данных с именем database_name , вы должны использовать следующую команду:

Мини — курс по виртуализации

Читайте также:  Windows 10 не меняется разрешение экрана 1024 768

Знакомство с VMware vSphere 7 и технологией виртуализации в авторском мини — курсе от Михаила Якобсена

Источник

MySQL: Create Database – Command Line

From this small tutorial you will learn how to create a MySQL database from the command-line in Linux.

I will show the general MySQL CREATE DATABASE syntax for creating a database with a default character set.

Additionally i will show how to create a user in MySQL, set him a password, grant all privileges on this newly created database and allow him to access it locally.

Cool Tip: Do you have a backup? You MUST have it! Backup MySQL databases from the command-line! This is really easy! Read more →

Log in to MySQL server from the command-line as root :

Create MySQL Database

Use the following syntax to create a database in MySQL:

Create a new user:

By specifying the localhost after the @ character we allow this user to connect to the MySQL database only from the server on which this database is hosted on.

You can change the localhost to an IP address or a hostname if you want to permit the user to connect to the database remotely.

Cool Tip: List MySQL users, their passwords and granted privileges from the command-line prompt! Read more →

Now you can log in to MySQL server from the command-line as this user:

To show the all databases available for the current user, run:

To access the newly created MySQL database, run:

You can also immediately access the database from the command-line by explicitly specifying its name:

To explicitly specify an IP address or a hostname of MySQL server, run:

Источник

Создание и удаление баз в MySQL/MariaDB

В данных примерах используется командная оболочка 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’;

Читайте также:  Digi usb anywhere linux

> UPDATE mysql.user SET Password=PASSWORD(‘new_password’) WHERE USER=’dbuser’ AND Host=’localhost’;

* все 3 команды меняют пароль для пользователя dbuser@localhost на новый — new_password.

При необходимости, удалить пользователя можно командами:

> REVOKE ALL PRIVILEGES, GRANT OPTION FROM ‘dbuser’@’localhost’;

> DROP USER ‘dbuser’@’localhost’;

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

Удаление базы MySQL

Удаление выполняется командой DROP DATABASE.

Командная консоль

Попробуем удалить ранее созданную базу:

> DROP DATABASE newdb;

phpMyAdmin

Выбираем нужную базу галочкой и кликаем по Удалить:

Источник

A Basic MySQL Tutorial

Published on June 12, 2012

About MySQL

MySQL is an open source database management software that helps users store, organize, and retrieve data. It is a very powerful program with a lot of flexibility—this tutorial will provide the simplest introduction to MySQL

How to Install MySQL on Ubuntu and CentOS

If you don’t have MySQL installed on your droplet, you can quickly download it.

How to Access the MySQL shell

Once you have MySQL installed on your droplet, you can access the MySQL shell by typing the following command into terminal:

After entering the root MySQL password into the prompt (not to be confused with the root droplet password), you will be able to start building your MySQL database.

Two points to keep in mind:

  • All MySQL commands end with a semicolon; if the phrase does not end with a semicolon, the command will not execute.
  • Also, although it is not required, MySQL commands are usually written in uppercase and databases, tables, usernames, or text are in lowercase to make them easier to distinguish. However, the MySQL command line is not case sensitive.

How to Create and Delete a MySQL Database

MySQL organizes its information into databases; each one can hold tables with specific data.

You can quickly check what databases are available by typing:

Your screen should look something like this:

Creating a database is very easy:

In this case, for example, we will call our database «events.»

In MySQL, the phrase most often used to delete objects is Drop. You would delete a MySQL database with this command:

How to Access a MySQL Database

Once we have a new database, we can begin to fill it with information.

The first step is to create a new table within the larger database.

Let’s open up the database we want to use:

In the same way that you could check the available databases, you can also see an overview of the tables that the database contains.

Since this is a new database, MySQL has nothing to show, and you will get a message that says, “Empty set”

How to Create a MySQL Table

Let’s imagine that we are planning a get together of friends. We can use MySQL to track the details of the event.

Let’s create a new MySQL table:

This command accomplishes a number of things:

  1. It has created a table called potluck within the directory, events.
  2. We have set up 5 columns in the table—id, name, food, confirmed, and signup date.
  3. The “id” column has a command (INT NOT NULL PRIMARY KEY AUTO_INCREMENT) that automatically numbers each row.
  4. The “name” column has been limited by the VARCHAR command to be under 20 characters long.
  5. The “food” column designates the food each person will bring. The VARCHAR limits text to be under 30 characters.
  6. The “confirmed” column records whether the person has RSVP’d with one letter, Y or N.
  7. The “date” column will show when they signed up for the event. MySQL requires that dates be written as yyyy-mm-dd

Let’s take a look at how the table appears within the database using the «SHOW TABLES;» command:

We can remind ourselves about the table’s organization with this command:

Keep in mind throughout that, although the MySQL command line does not pay attention to cases, the table and database names are case sensitive: potluck is not the same as POTLUCK or Potluck.

Читайте также:  Папка данных приложений windows

How to Add Information to a MySQL Table

We have a working table for our party. Now it’s time to start filling in the details.

Use this format to insert information into each row:

Once you input that in, you will see the words: Let’s add a couple more people to our group:

We can take a look at our table:

How to Update Information in the Table

Now that we have started our potluck list, we can address any possible changes. For example: Sandy has confirmed that she is attending, so we are going to update that in the table.

You can also use this command to add information into specific cells, even if they are empty.

How to Add and Delete a Column

We are creating a handy chart, but it is missing some important information: our attendees’ emails.

We can easily add this:

This command puts the new column called «email» at the end of the table by default, and the VARCHAR command limits it to 40 characters.

However, if you need to place that column in a specific spot in the table, we can add one more phrase to the command.

Now the new “email” column goes after the column “name”.

Just as you can add a column, you can delete one as well:

I guess we will never know how to reach the picnickers.

How to Delete a Row

If needed, you can also delete rows from the table with the following command:

For example, if Sandy suddenly realized that she will not be able to participate in the potluck after all, we could quickly eliminate her details.

Notice that the id numbers associated with each person remain the same.

Источник

Linux mysql create database

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() .

Источник

Оцените статью