Mariadb создание базы данных windows

Синтаксис

CREATE [OR REPLACE] {DATABASE | SCHEMA} [IF NOT EXISTS] db_name
    [create_specification] ...

create_specification:
    [DEFAULT] CHARACTER SET [=] charset_name
  | [DEFAULT] COLLATE [=] collation_name

Contents

  1. Синтаксис
  2. Описание
    1. OR REPLACE
    2. IF NOT EXISTS
  3. Примеры
  4. Смотри также

Описание

CREATE DATABASE создает базу данных с заданым именем. Для того чтобы использовать данное выражение, Вам необходимо обладать соответствующими привилегиями (En). CREATE SCHEMA — это синоним выражения CREATE DATABASE. Если использовано выражение IF NOT EXISTS, то в ситуации, когда база данных уже существует, пользователю будет выдано предупреждение, а не сообщение об ошибке.

OR REPLACE

MariaDB starting with 10.1.3

Выражение OR REPLACE было добавлено в MariaDB в версии 10.1.3.

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

DROP DATABASE IF EXISTS db_name;
CREATE DATABASE db_name ...;

IF NOT EXISTS

При использовании выражения IF NOT EXISTS MariaDB вернет предупреждение, а не сообщение об ошибке в том случае, если база с указанным именем уже существует.

Примеры

CREATE DATABASE db1;
Query OK, 1 row affected (0.18 sec)

CREATE DATABASE db1;
ERROR 1007 (HY000): Can't create database 'db1'; database exists

CREATE DATABASE IF NOT EXISTS db1;
Query OK, 1 row affected, 1 warning (0.01 sec)

SHOW WARNINGS;
+-------+------+----------------------------------------------+
| Level | Code | Message                                      |
+-------+------+----------------------------------------------+
| Note  | 1007 | Can't create database 'db1'; database exists |
+-------+------+----------------------------------------------+

Настройка кодировки и правил сортировки (En). Подробнее смотри на странице «Настройка кодировки и правил сортировки» (En).

CREATE DATABASE czech_slovak_names 
  CHARACTER SET = 'keybcs2'
  COLLATE = 'keybcs2_bin';

Смотри также

  • DROP DATABASE (En)
  • ↑ CREATE ↑

Comments

Content reproduced on this site is the property of its respective owners,
and this content is not reviewed in advance by MariaDB. The views, information and opinions
expressed by this content do not necessarily represent those of MariaDB or any other party.

MariaDB is the most versatile open-source relational database management system (DBMS) that can be used in place of the widely used MySQL database technology. It was developed as a clone of MySQL by developers who were instrumental in the original database’s development; they formed MariaDB in 2009 in response to Oracle Corp.’s acquisition of MySQL, when they saw a threat to open source development to MySQL. In this guide we will show the steps to MariaDB create database.

Much of the development work on the open source database has focused on achieving feature parity between MariaDB vs MySQL. MariaDB Corp., the driving force behind MariaDB, says that “for all practical purposes”. As a result, most users can switch between the two technologies simply by uninstalling MySQL and installing MariaDB in its place. In this article, we will create a MariaDB database without much ado; let us get started.

Features of MariaDB Database

  • Supports Major SQL Statements
  • Several Queries can be executed in Parallel.
  • Supports Thread Pooling Concept – Thread Pooling accelerates work on MariaDB when many connections to the database are used. Rather than creating a new thread for each connection, MariaDB makes use of a pool of previously opened threads. A new connection creates a thread for the query and sends it. All searches become more efficient and offer more accurate results. MySQL provides a comparable feature; however, it is only available in the Enterprise edition, which is a costly upgrade. It is completely free in MariaDB. 
  • Support for Database Views
  • Virtual Columns’ Support – The support for virtual columns is one of MariaDB’s most notable features. At the database level, such columns can do calculations. Users won’t have to write computations in each app independently when multiple apps use the same column. Instead, it will be handled by the database.
  • Feature of ColumnStore supported – The feature of ColumnStore enables better storage of massive volumes of data across the cluster. This also improves the overall performance of the cluster through horizontal scaling improvement.  
  • Supports Data Compression using Flash Storage – The RocksDB database is added to MariaDB via the MyRocks storage engine. This database compresses data more efficiently and so performs better in flash storage.

Major Organizations using MariaDB Database

ServiceNow, DBS Bank, Google, Mozilla, the Wikimedia Foundation are some of the major organizations using MariaDB.

MariaDB is included in a number of Linux distributions and BSD operating systems. Several distributions, including Arch Linux, Manjaro, Debian, Fedora, Red Hat Enterprise Linux, CentOS, Mageia, OpenSUSE, SUSE Linux Enterprise Server, OpenBSD, and FreeBSD, make MariaDB the default database.

Mariadb Database Use Cases

MariaDB finds its usage in ad-hoc analytics, Data Marts for Hadoop, Self service analytics and smart transactions. Also, read the article on setting up Azure MariaDB in the cloud.

MariaDB Enterprise can be used as a data warehouse or analytics database, utilising columnar storage and massively parallel processing (MPP) to execute interactively, without the need to create indexes ad hoc queries can be executed on hundreds of billions of rows – and all using standard SQL (including joins). Additionally, MariaDB Enterprise utilises a cloud-native storage architecture and offers the option of using Amazon S3 compatible object storage to reduce costs and take advantage of unlimited capacity.

Install MariaDB Database on Windows

Download MariaDB

MariaDB can be installed from the official repository. At the time of writing this article, the stable version was 10.6.4. However, the Windows installer is not working, and we will be using an older version for the installation of our windows.

Installing MariaDB on Windows

For windows, we will be using version 10.5.12. After you download the msi installer, click on it and click next. It is quite easy to install on windows.

mariadb create database

Click on next till you reach the window as shown below.

MariaDB installation on Windows

The above window gives you an advanced option to select various features. Leave it as default in case you don’t understand much. Click on next, and you will be directed to a window where you have to provide a password for the root.

install mariadb database

You will be required to provide a root password in case you opted for a DB instance in the Custom setup window. Here you can also enable access from the remote machine for the root user. Click on next, and you will be routed to default instance properties.

setup mariadb windows

You can configure the service name along with the port. You can also configure Innodb settings here. If you are a beginner, then leave it as default values and click next and install it.

Installing MariaDB on MacOS

For macOS, you will need brew for installing MariaDB. In case you don’t have homebrew installed in your macOS, then follow the instructions here. Now follow the instructions after homebrew has been installed. First, of all install MariaDB using brew.

After installing MariaDB, start MariaDB.

To automatically start the MariaDB Server every time on restart (also known as a background service):

				
					brew services start mariadb
				
			

After MariaDB Server is started, you can log in as your user:

To login as root (no password is initially set):

You will get a MariaDB command console as shown below. 

Installing MariaDB on MacOS

Install MariaDB Database on Ubuntu Server

To install on Ubuntu follow the instructions. First update the package list.

Next we will install the mariadb.

				
					sudo apt install mariadb-server
				
			

Once the mariadb is installed, it will be automatically started. You can check the status by running the following command.

				
					sudo systemctl status mariadb
				
			

mariadb installation on ubuntu

MariaDB Create Database

For the creation and deletion of the database in MariaDB, you will require local admin privileges if running on Windows and root admin if running on Linux. You can also read the article about installing MariaDB Windows in the cloud (Azure, AWS, GCP)

Once MariaDB has been installed, run the MariaDB console and use the following command:

Provide the password which you gave during the installation process.

mariadb create database

				
					CREATE DATABASE databasename;
				
			

				
					CREATE DATABASE Logistics;
				
			

Incase you are not sure whether the database exists or not you can add Replace with Create

				
					CREATE OR REPLACE DATABASE Logistics;
				
			

You can also use DROP and CREATE database incase you are not sure.

				
					DROP DATABASE logistics;
CREATE DATABASE logistics;
				
			

You can provide a check before creating a database to ensure whether the database has been previously created or not.

				
					CREATE DATABASE IF NOT EXISTS logistics;
				
			

You can check all the created databases by using the following command:-

MariaDB Create Database Steps Finished

The biggest advantage of using MariaDB is that it was created as a clone of MySQL. It is easy to migrate the MySQL database to MariaDB. MySQL fans won’t be disappointed. Most of the MySQL syntaxes and commands are retained in MariaDB. You can read more about Maria DB installation in the article MariaDB cloud.

MariaDB is a versatile Database and provides support for various applications from modern-day NoSQL databases to traditional relational databases. The learning curve is easy. MariaDB can be used to build and deploy a variety of applications.

Despite a lot of support for MySQL, there are still many drawbacks, and it requires some consideration before selecting MariaDB. Issues such as compatibility with the latest version of MySQL is a challenging issue. So, people who are migrating from the latest version of MySQL would still have to re-code some of their databases to migrate them to MariaDB. Its caching mechanism still requires some improvement. Its central Indexing file becomes heavy after some time, causing performance issues for the entire database. Despite all these issues, it looks promising database alternative when opting for complete open-source database solutions.

In this MariaDB tutorial, we will discuss, how to create a database from an SQL file in MariaDB.

  • MariaDB create database from sql file Windows
  • MariaDB create database from SQL file Ubuntu and Linux

In MariaDB, we can create the database from the SQL file, this SQL file contains the command to create the database. The SQL file is saved with extension (xyz.sql).

Let’s write the SQL command to create the database in the file, open Notepad text editor.

CREATE DATABASE sqldatabase;
create database from SQL file in mariadb

MariaDB sql file

Open the HeidiSQL application and Load the SQL file by clicking on the Folder icon below the menu section.

MariaDB create database from sql file

MariaDB HeidiSQL sql file loading

After performing the above steps, a MariaDB: Confirm dialogue will appear to select the encoding method. Then select Yes.

MariaDB create database from sql file

MariaDB MariaDB confirm

Then click on the play icon below the menu section to execute the command in the SQL file.

How to create database from sql file in MariaDB

MariaDB create database from sql file windows

After clicking on Execute button, it will create the database in the current session.

This is how to create a database from an SQL file in MariaDB in Windows.

Read MariaDB Insert Into

MariaDB create database from SQL file Ubuntu and Linux

Ubuntu users follow this section to create a database in MariaDB from sql file using the below steps.

Now open the gedit editor on Ubuntu and write the below line in that file. Save the file with the name us.sql.

MariaDB create database from SQL file Ubuntu and Linux

MariaDB united state database

Open the MariaDB prompt in the terminal using the below command and enter the password if it asks.

mysql -u root -p

After login into the MariaDB shell prompt, Create the new database as us_database.

CREATE DATABASE us_database;

Then exit from the MariaDB shell or return to the Ubuntu terminal.

create database from SQL file in mariadb

MariaDB us database

In the Ubuntu terminal, write the below command to create a database from an SQL file.

mysql -u root -p us_database < us.sql

Now again log into the MariaDB shell prompt and run the below command to show the created database that is united_states.

SHOW DATABASES;
MariaDB create database from SQL file ubuntu

MariaDB create database from SQL file ubuntu

The output shows that created database as united_states in the pink color.

This is how to create a database from SQL file Ubuntu and Linux in MariaDB.

You may like the following MariaDB tutorials:

  • MariaDB create procedure
  • How to Change Column in MariaDB
  • MariaDB Update Statement
  • How to Remove User in MariaDB
  • How to Grant All Privileges in MariaDB
  • MariaDB Primary Key With Examples

So in this MariaDB tutorial, we have learned about the “MariaDB create a database from sql file” and covered the following topics.

  • MariaDB create database from sql file Windows
  • MariaDB create database from SQL file Ubuntu and Linux

I am Bijay having more than 15 years of experience in the Software Industry. During this time, I have worked on MariaDB and used it in a lot of projects. Most of our readers are from the United States, Canada, United Kingdom, Australia, New Zealand, etc.

Want to learn MariaDB? Check out all the articles and tutorials that I wrote on MariaDB. Also, I am a Microsoft MVP.

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

Обновлено:
Опубликовано:

Тематические термины: MySQL, MariaDB, phpMyAdmin.

В данных примерах используется командная оболочка mysql и phpMyAdmin.

Подключение к СУБД
Создание новой базы
    Командная строка
    phpMyAdmin
Создание пользователя
Удаление базы
    Командная строка
    phpMyAdmin
Дополнительные материалы

Если работа ведется на продуктивном сервере баз данных, и особенно, при необходимости что-то отредактировать или удалить, рекомендуется сделать резервные копии.

Подключение к СУБД

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

а) В Linux вводим команду:

mysql -uroot -p

* где root — пользователь, под которым мы будем подключаться к оболочке; ключ -p потребует ввода пароля.

В некоторых случаях (и если работаем от root) достаточно будет просто ввести:

mysql

Мы окажемся в оболочке SQL без необходимости ввода логина и пароля.

б) В Windows запускаем командную строку — в меню пуск или найдя ее в поиске. Переходим в каталог, с установленной СУБД и запускаем одноименную команду mysql, например:

cd «%ProgramFiles%\MySQL\MySQL Server 8.0\bin\»

* в данном примере предполагается, что у нас установлена MySQL версии 8.0. 

mysql -u root -p

* здесь, как и в Linux, идет подключение к mysql/mariadb под учетной записью root с запросом пароля.

Создание новой базы

Для создания базы используется SQL-запрос CREATE DATABASE. Рассмотрим подробнее его использование.

Командная строка

Используйте данный шаблон команды:

> CREATE DATABASE newdb DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci;

* вышеописанная команда создаст базу данных с названием newdb и кодировкой UTF-8 (самая распространенная и универсальная).

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

> show databases;

* данная команда выводит в консоль список баз, созданных в СУБД.

Подключиться к базе можно командой:

use newdb

phpMyAdmin

В phpMyAdmin переходим в раздел Базы данных — вводим название новой базы — выбираем кодировку и нажимаем Создать:

Создаем базу данных в phpMyAdmin

Настройка прав доступа

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

> CREATE USER ‘dbuser’@’localhost’ IDENTIFIED BY ‘password’;

> GRANT ALL PRIVILEGES ON newdb.* TO dbuser@localhost;

* где:

  • dbuser@localhost — имя учетной записи, которая будет подключаться с локального сервера.
  • password — придуманный нами пароль.
  • newdb.* — наша база и все ее таблицы.

** В данном примере, учетной записи будут предоставлены полные права (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’;

> 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’;

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

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

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

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

> DROP DATABASE newdb;

phpMyAdmin

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

Удаляем базу MySQL в phpMyAdmin

Читайте также

Другие инструкции по MySQL / MariaDB:

1. Как сделать дамп базы MySQL / MariaDB.

2. Как восстановить базу MySQL / MariaDB.

3. Создание пользователей MySQL/MariaDB и предоставление прав доступа.

Summary: in this tutorial, you will learn how to use the MariaDB create database statement to create a new database.

Introduction to the MariaDB create database statement

To create a new database in a MariaDB server, you use the create database statement with the following syntax:

create [or replace] database [if not exists] database_name
Code language: SQL (Structured Query Language) (sql)

[character set = charset_name]

[collate = collation_name];

In this syntax:

First, specify the name of the database that you want to create after the create database keywords. The database name must be unique in the MariaDB server instance. If you create a database that has the same name as an existing database, MariaDB will issue an error.

Second, the optional or replace clause instructs MariaDB to drop the database first if it exists before creating the new database. It is a shortcut for the following statements:

drop database if exists database_name;
create database database_name;
Code language: SQL (Structured Query Language) (sql)

Note that MariaDB has supported the or replace clause since version 10.1.3.

Third, use the if not exist option to conditionally create a database if it does not exist. In other words, if you try to create a database that already exists with the if not exist option, MariaDB will do nothing.

Finally, optionally specify a character set and collation for the new database. A character set defines how and which characters that the database will store to support particular languages. A collation defines the rule for comparing strings, for example, the letter a appears before the letter b, etc.

Notice that you need the create privilege for the database in order to create a new database.

Creating a new database using mysql command-line program

To create a new database via the mysql command-line program, you follow these steps:

First, log in to the MariaDB server using a user account that has the create privilege for the database:

>mysql -u root -p
Enter password: ********
Code language: SQL (Structured Query Language) (sql)

Type the password for the root user and hit the Enter keyboard.

Second, show databases in the current server using the show databases statement:

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| nation             |
| performance_schema |
| test               |
+--------------------+
5 rows in set (0.01 sec)
Code language: SQL (Structured Query Language) (sql)

Third, create a new database name crm:

mysql> create database crm;
Query OK, 1 row affected (0.01 sec)
Code language: SQL (Structured Query Language) (sql)

Fourth, show the databases again:

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| crm                |
| information_schema |
| mysql              |
| nation             |
| performance_schema |
| test               |
+--------------------+
6 rows in set (0.00 sec)
Code language: SQL (Structured Query Language) (sql)

The database crm is on the list.

After creating the new database, you can select the database as the current database to work with.

In this tutorial, you have learned how to use the MariaDB create database statement to create a new database.

Was this tutorial helpful ?

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Openvpn static ip client windows
  • Как разблокировать usb порт на компьютере windows 10
  • Windows microsoft windows defender offline
  • 866660 credssp windows 10
  • Как поменять иконки на свои windows 10