Datagrip как создать базу данных
Перейти к содержимому

Datagrip как создать базу данных

  • автор:

Quick start with DataGrip

This quick start guide will introduce you to the key concepts and help you with your first steps in DataGrip.

Also, you can check our introduction video that covers all major topics about the IDE: adding data sources, configuring connection options, working in the editor, and installing plugins.

Prerequisites

To complete this quick start guide, ensure that you have installed the following software:

Git — https://git-scm.com/ (if you plan to use Sakila dump files on Step 4)

Step 1. Create a new project

When you open DataGrip, you see the Welcome screen.

DataGrip displays the Welcome screen when no project is opened. For example, when you run DataGrip for the first time or when you close the only open instance of a project. From this screen, you can create a new project, open an existing project, or clone files from a Version Control System (VCS).

Creating a project

Create a new project by clicking the New Project button. A new project in DataGrip is a complex of your data sources, console and scratch files, and attached folders.

Alternatively, click Open to open a directory with an existing project.

In the Enter new project name field, type the name of your project.

After the project is created and opened, you will see an IDE interface with all tool windows hidden. Tool windows are tabs that are attached to the bottom and sides of the IDE window. You can rearrange and even detach them to use as separate windows, for example, on another monitor.

Tool windows provide access to development tasks: viewing your database structure, running and debugging your application, integration with version control systems and other external tools, code analysis, search, navigation, and so on.

Opening the database explorer

Expand Files and Database Explorer tool windows by clicking their tabs.

Step 2. Connect to a database

Depending on a database vendor (MySQL, PostgreSQL, Oracle), you need to create a corresponding data source connection. In this tutorial, we will use SQLite because, for other databases, you need a running instance of the database. It means that you need to install and configure them before creating a connection.

A database in SQLite is a single disk file. The file format is cross-platform. A database that is created on one machine can be copied and used on a different machine with a different architecture. DataGrip can create this file for you. So, all you need is to download drivers. The file default name is identifier.sqlite but you can change it.

If you want to connect to other database management systems (DBMS), refer to Create connection.

Open data source properties. You can open data source properties by using one of the following options:

Navigate to File | Data Sources .

In the Database Explorer ( View | Tool Windows | Database Explorer ), click the Data Source Properties icon .

On the Data Sources tab in the Data Sources and Drivers dialog, click the Add icon () and select SQLite .

Check if there is a Download missing driver files link at the bottom of the data source settings area. As you click this link, DataGrip downloads drivers that are required to interact with a database. The IDE does not include bundled drivers in order to have a smaller size of the installation package and to keep driver versions up-to-date for each IDE version.

You can specify your drivers for the data source if you do not want to download the provided drivers. For more information about creating a database connection with your driver, see Add a user driver to an existing connection.

To ensure that the connection to the data source is successful, click the Test Connection link.

To connect to an existing SQLite database, specify a file path to the database file in the File field. Also, to create a database, you can drag an SQLite DB file to the Database Explorer .

As the data source is ready, you will see it in the Database Explorer . The data source is presented as a tree with nodes. Also, along with the data source, DataGrip creates a query console. Query consoles are SQL files in which you can compose and execute SQL statements. They are already attached to your data source, unlike usual SQL files. So, you can start writing your queries to a database right away.

query console

Step 3. Attach a directory with SQL scripts

To run SQL scripts, you can right-click the data source and select SQL Scripts | Run SQL script . Alternatively, you can attach a folder with these scripts to the Files tool window and run them from here.

For illustration purposes, we will use Sakila dump files. You can get them by cloning the dumps repository. Note that you need to install Git to clone the repository.

Navigate to View | Tool Windows | Files on the menu.

In the Files tool window, right-click any area and select Attach Directory to Project .

Navigate to the directory that you want to attach. In our case, it is the dumps directory.

Also, to attach a directory, navigate to File | Open on the menu bar and select the directory in the file browser. You can find the attached directory in the Files tool window ( View | Tool Windows | Files ).

Step 4. Run dump files

The dumps repository includes scripts that generate the structure of the Sakila database and scripts that add data to database objects. Let’s run a script that generates objects in the main schema.

In the Files ( View | Tool Windows | Project ) tool window, navigate to the sqlite-sakila-db tree node.

Expand sqlite-sakila-db tree node.

Right-click the sqlite-sakila-schema.sql file and select Run ‘sqlite-sakila-schema. ‘ . Alternatively, press Ctrl+Shift+F10 .

In the Target data source / schema table, click the Add button () and select SQLite .

Step 5. Write your code

As you work in the editor, DataGrip analyzes your code, searches for ways to optimize it, and detects potential and actual problems. The following list includes basic features and tools that might be useful for your code writing and increase your productivity:

Code completion

Suggestions for code completion appear as you type your code. DataGrip has two types of code completion:

Basic code completion Ctrl+Space helps you complete names of tables, routines, types, and keywords within the visibility scope. When you invoke code completion, DataGrip analyzes the context and suggests the choices that are reachable from the current caret position. By default, DataGrip displays the code completion popup automatically as you type.

Smart code completion Ctrl+Shift+Space filters the suggestions list and shows only the types applicable to the current context.

The following animation shows the difference between basic and smart completion. Notice the number of variants that are suggested for different completion types

Generating code

DataGrip provides multiple ways to generate common code constructs and recurring elements, which helps you increase productivity. These can be either file templates used when creating a new file, custom or predefined live templates that are applied differently based on the context, various wrappers, or automatic pairing of characters.

From the main menu, select Code | Generate Alt+Insert to open the popup menu with available constructs that you can generate.

You can generate functions, procedures, views, and other database objects.

To generate an object, press Alt+Insert and select the object that you want to generate.

Live templates

Use live templates to insert common constructs into your code, such as statements or definitions of database objects.

The following video shows how you can use live templates.

To expand a code snippet, type the corresponding template abbreviation and press Tab . Keep pressing Tab to jump from one variable in the template to the next one. Press Shift+Tab to move to the previous variable.

To see the list of live templates, open settings Ctrl+Alt+S and navigate to Editor | Live templates .

Inspections

In DataGrip, there is a set of code inspections that detect and correct abnormal code in your project before you compile it. The IDE can find and highlight various problems, locate dead code, find probable bugs, spelling problems, and improve the overall code structure.

Inspections can scan your code in all project files or only in specific scopes (for example, only in production code or in modified files).

Every inspection has a severity level — the extent to which a problem can affect your code. Severities are highlighted differently in the editor so that you can quickly distinguish between critical problems and less important things. DataGrip comes with a set of predefined severity levels and enables you to create your own.

To see the list of inspections, open settings Ctrl+Alt+S and navigate to Editor | Inspections . Disable some of them, or enable others, plus adjust the severity of each inspection. You decide whether it should be considered an error or just a warning.

For example, the Redundant code in COALESCE call inspection reports all the arguments except for the first expression that does not evaluate to NULL.

Intention actions

As you work in the editor, DataGrip analyzes your code, searches for ways to optimize it, and detects potential and actual problems.

As soon as the IDE finds a way to alter your code, it displays a yellow bulb icon in the editor next to the current line. By clicking this icon, you can view intention actions available in the current context. Intention actions cover a wide range of situations from warnings to optimization suggestions. You can view the full list of intentions and customize them in the Settings dialog Ctrl+Alt+S .

To see the list of intention actions, open settings Ctrl+Alt+S and navigate to Editor | Intentions .

Click the light bulb icon (or press Alt+Enter ) to open the list of suggestions.

Select an action from the list and press Enter .

For example, you can use an intention action in the INSERT statement to create a table with valid field types:

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

кто-нибудь знает как создать новую базу в DataGrip (IDE базы данных от JetBrains)? Не удалось найти в страница справки DataGrip.

5 ответов

только из raw SQL на данный момент, нет пользовательского интерфейса для этого.

на DataGrip 2017.1 UI для этого был введен

enter image description here

сначала определите базу данных. Файл —> источники данных и драйверы — > нажмите на зеленую » + » в левом верхнем углу, чтобы выбрать тип базы данных. А затем заполните все настройки на вкладке «Общие».

например, для PostgreSQL:

базы данных: базы данных Postgres

Как только вы настроены, Ctrl+Shift+F10, чтобы открыть консоль, и вы можете ввести свой SQL заявления, например:

Я не верю, что существующие ответы охватывают MySQL. В MySQL, создание новой схемы эквивалентно созданию новой базы данных. В этом случае контекстный щелчок (обычно щелчок правой кнопкой мыши) на вашем соединении в дереве навигации и выберите New | Schema. Дайте ему имя и выполнить в базе данных».

имя этой схемы будет отображаться в дереве навигации, и вы можете добавить таблицы, данные и т. д.

сложная часть создания новой базы данных заключается в том, что вы должны сделать это с помощью DataGrip «источник данных», где подключены как пользователь, который имеет привилегию для создания базы данных, которая обычно является пользователем «admin», который вы добавили, когда вы впервые установили Postgres, который подключен к основной базе данных «postgres».

мне нравится отслеживать все команды, которые я запустил, прикрепляя новый каталог (меню «Файл» / «прикрепить каталог») и создавая новые файлы с описательным имена, такие как «create_my_test_db.SQL» и введите SQL для создания базы данных:

Если вы хотите выполнить этот код, убедитесь, что вы используете правильную «консоль». DataGrip имеет раскрывающееся меню в правом верхнем углу над меню файла, поэтому убедитесь, что вы выбрали «postgres@localhost», так как это источник данных пользователя, который имеет права на создание новой базы данных.

аналогично, чтобы создать нового пользователя для этой базы данных, создайте новый sql файл «create_my_test_db_user.в SQL»

затем вы можете создать новый источник данных и установить свойства host = localhost, user = my_test_db_user и password = keyboard_cat.

Datagrip как создать базу данных

image

image

image

image

image

Options

image

Schemas

image

image

image

image

image

image

image

image

image

image

image

image

image

image

image

Detailed tutorial about how to create your own custom Theme.
Blog post about creating custom themes for IntelliJ Platform

image

image

Getting Started with JetBrains DataGrip on a Distributed SQL Database

If you’re a database developer, you know the time saving value of an IDE in helping you create and navigate database objects, plus query and edit data from single UI. DataGrip from JetBrains is a well-rounded, visual database tool that supports almost 20 SQL and NoSQL databases from a single interface. And because YugabyteDB is PostgreSQL compatible, getting DataGrip to work with a distributed SQL database is relatively simple. In this post we’ll show you how to get DataGrip connected to a YugabyteDB cluster, use it to build a sample database, load it up with data and browse it.

What’s YugabyteDB? It is an open source, high-performance distributed SQL database built on a scalable and fault-tolerant design inspired by Google Spanner. Yugabyte’s SQL API (YSQL) is PostgreSQL wire compatible.

Introducing DataGrip

yugabytedb and datagrip

DataGrip boasts many of the must-have features you’d expect from a database GUI tool including:

  • Support for Multiple Databases – DataGrip is the multi-engine database environment. If the DBMS has a JDBC driver you can connect to it via DataGrip. It provides database introspection and various instruments for creating and modifying objects for the supported engines.
  • Database Objects – DataGrip introspects all objects in your databases and displays them in folders grouped by schemas. It also provides a UI for adding and editing tables, columns, indexes, constraints, etc.
  • Database Editor – The powerful data editor lets you add, remove, edit, and clone data rows. Navigate through the data by foreign keys and use the text search to find anything in the data displayed in the data editor.
  • Navigation – Quick navigation takes you to an object independent of whether it has just been created in your code, or it has already been read from a database. Navigate to the symbol action which lets you find objects by their name.
  • Writing SQL – DataGrip boasts a smart text editor, code completion, automatic code generation, code analysis, refactoring, and a variety of visual themes to suit your preferences.
  • Additional Features – DataGrip also has a query console, diff viewer, import/export wizards, VCS, and ER diagramming capabilities.

JetBrains offers a 30 day free trial, so you can try all the features before deciding if you’d like to sign on for a commercial subscription, which is very reasonably priced. Ok, let’s dive in and get DataGrip installed and connected to a YugabyteDB cluster!

Step 1: Install a Local YugabyteDB Cluster

Before we get into DataGrip, you’ll need to setup YugabyteDB and install a sample database. Although for the purposes of this blog post we’ll be installing everything on a macOS, both YugabyteDB and DataGrip support most major operating systems.

For complete instructions on how to get up and running on a variety of platforms including prerequisites, check out our Quickstart Guide. In the following section we’ll cover the basic steps for getting up and running in just a few minutes with a local 3 node cluster on your Mac laptop.

Download and Extract YugabyteDB

Note: At the time of this writing, 2.0.11 is the latest release of YugabyteDB. Make sure to check the Quickstart Guide for the latest version.

Configure Loopback Addresses

Add a few loopback IP addresses for the various YugabyteDB processes to use.

Create a 3 Node Cluster

With the command below, create a 3 node cluster with a replication factor of 3.

You can verify that your cluster is up and running by checking out the YugabyteDB Admin UI which is located at:

yugabytedb cluster creation confirmed

Step 2: Download and Install DataGrip

DataGrip can be downloaded from their website here:

As of this writing, version 2019.3.3 is what was tested against YugabyteDB. The installation is as simple on Mac as you’d expect.

installing datagrip for yugabytedb on a mac

Step 3: Connecting DataGrip to YugabyteDB

Next, you’ll want to configure a new database connection. Click on “+” > Datasource > PostgreSQL.

configuring yugabyte in datagrip

Configure the connection to YugabyteDB using the following values:

  • Name: YugabyteDB
  • Server Host or IP: localhost
  • Port: 5433 (Note that PostgreSQL’s default port assignment is 5432, while YugabyteDB uses 5433)
  • Database User: “yugabyte” is YugabyteDB’s default user
  • Password: None (by default)
  • Database: “postgres”

Select “Introspect using JDBC metadata”

On the “Options” tab you’ll want to check the “Introspect using JDBC metadata” box. YugabyteDB does not use PostgreSQL’s system columns given that these functions are handled by the DocDB storage engine of YugabyteDB. This option makes DataGrip’s PostgreSQL connector use standard JDBC metadata as opposed to PostgreSQL specific metadata.

Of course, it is always a good idea to test the connection to make sure everything is set up correctly before proceeding. Click the OK button and you are now ready to start exploring DataGrip.

Step 4: Create the Northwind Database

For the purposes of this blog post we’ll be using the Northwind sample database. You can download the DDL and data scripts here. Once you have downloaded the files, building the Northwind database on YugbyteDB is simple:

Open up a New Console in DataGrip and Create the Northwind Database

Right-click on YugabyteDB in the tree and select New Database. Name it northwind and execute.

Creating the Northwind Database YugabyteDB and DataGrip Example

Build the Northwind Tables and Objects

Click on YugabyteDB > northwind > Run SQL Script and load the DDL script to create the Northwind database objects.

Creating the Northwind database objects YugabyteDB DataGrip

At the end of the script execution you should see something like:

Load the Northwind Database with Data

Once again, click on YugabyteDB > northwind > Run SQL Script and load the DML script to load the Northwind database with data.

At the end of the script execution you should see something like:

Step 5: Test Drive DataGrip against a YugabyteDB Cluster

The first thing we can look at is a tree view of our database objects.

Tree view database objects YugabyteDB DataGrip how to

Expanding out a table allows us to inspect column properties and other attributes.

Expanding a table yugabytedb datagrip northwind how to

We can view the data in a table by simply double-clicking on a table in the tree.

Viewing data datagrip yugabytedb northwind example

Finally, we can run queries against the database by right clicking on northwind in the tree and selecting a New Console. For example, below we issued:

run queries yugabytedb datagrip northwind how to

That’s it! You can learn more about DataGrip’s features here, plus work through some of their tutorials on their Docs site.

Creating new database in DataGrip JetBrains

Anybody know how to create new database in DataGrip (database IDE from JetBrains)? Could not find in DataGrip Help page.

5 Answers 5

In DataGrip 2017.1 UI for this was introduced

enter image description here

You first define the database. File —> Data Sources and Drivers —> Click on the green ‘+’ in the top left corner to select the database type. And then fill in all the settings in the ‘General’ tab.

For example for PostgreSQL:

Once you are set up, Ctrl+Shift+F10 to open the console and you can type your SQL statements, e.g.:

USER_1's user avatar

I don’t believe the existing answers cover MySQL. In MySQL, creating a new schema is equivalent to creating a new database. For this case, contextual-click (usually right-click) on your connection in the navigation tree and choose New | Schema. Give it a name and ‘Execute in database».

The name of this schema will show up in the navigation tree and you can then add tables, data, etc.

HumanJHawkins's user avatar

The tricky part of creating a new database, is that you have to do it using a DataGrip «Data Source» where are are connected as a user that has the priviledge to create a database, which is generally the «admin» user that you added when you first installed Postgres which is connected to the main «postgres» database.

I like to keep track of all the commands I have run by attaching a new directory (File Menu | Attach Directory) and creating new files with descriptive names, such as «create_my_test_db.sql» and enter the sql to create the database:

When you want to execute this code, make sure that you are using the correct «console». DataGrip has a drop-down menu in the upper-right corner above your file menu, so make sure you have selected «postgres@localhost», since this is the user Data Source that has privileges to create a new database.

Similarly, to create a new user for this data base, create a new sql file «create_my_test_db_user.sql»

Then you can create a new Data Source, and set the properties to host = localhost, user = my_test_db_user, and password = keyboard_cat.

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

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