Phpstorm как подключить mysql

PHPStorm подключаемся к mysql БД

Нет ничего проще чем настройка подключения к MySQL БД в IDE PHPStorm. На самом деле интуитивно понятный интерфейс и малое количество действие уже заранее обеспечили вам простую настройку. Так что данная статья, я так думаю, пригодится тем, у кого всё же возникли проблемы с настройкой соединения с БД в шторме.

Чтобы не было недопониманий, сразу сообщу, что подключаться мы будем к локальной БД развёрнутой в OpenServer. Ну на самом деле с удалёнными БД проблем быть не должно. Читаем далее, я обязательно напомню об этом моменте.

Начинаем

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

Обратите внимание, в правой панели у вас есть пункт Database. Кликнув по нему у вас откроется панель с подключёнными БД. В вашем случаем там будет пустота.

Вверху панели находим иконку с «+» и кликаем по ней. У вас откроется меню, в котором нужно выбрать тип БД с которым собираемся работать.

Я же выберу MySQL, как это и было сказано в названии статьи.

После выбора у вас откроется окно настройки соединения. Если у вас версия шторма без каких либо плагинов и просто версия «из коробки», то скорее всего вам потребуется установка специального драйвера для работы с БД. К счастью вам не нужно открывать браузер, залезать в гугл и искать непонятно что, непонятно где. Просто в самом низу находим ссылку «download missing driver file». Кликаем по ней и необходимый драйвер сам загрузится и установится в течении пары секунд.

После этого вам необходимо заполнить 4 поля.

НО! Бывают такие случаи, как например у меня. Что вы работаете на локальном сервере, но у вас открыт доступ из для сети. В таком случае узнаёте IP адрес сервера и указываете его, у меня например получилось 192.168.0.102.

Следующее поле будет Database. Тут проблем думаю не возникнет, имя БД вы узнаёте в том же самом PhpMyAdmin или Heidisql

Ну у меня есть БД под названием WP, собственно его я и введу.

После того как с полями будет покончено, рекомендую проверить соединение. Кликнув по кнопке Test Connection.

Там 2 варианта, либо Successful, либо Failed. У меня в первый раз выпала ошибка. Как раз по той причине, что у меня сервер открыт для сети) А я использовал localhost. Но просто поменяв IP, всё заработало. Так что проверьте всё на всякий случай.

Ну и в самом конце жмём на ОК.

Окно настройки у вас закроется, а в панели списка БД появится пункт с названием базы к которой вы пытались настроить соединение. Двойным кликом по нему вы можете развернуть и посмотреть все содержащиеся таблицы с и их полями.

Ксати, чтобы поменять что-то в настройках к данному соединению, то вам достаточно кликнуть по нему правой кнопкой мыши и выбрать пункт Properties. Благодаря чему у вас снова откроется окно настроек соединения.

Собственно всё. Если же у вас возникаю какие либо проблемы, то тогда ещё раз проверьте настройки. Если это локальный сервер, то убедитесь, что он запущен, а так же что вы верно к нему подключаетесь. Если же это удалённая БД, то проверьте соединение к ней, ну например при помощи HeidiSQL

Так же подписывайтесь на PUSH оповещения (окошко которое всплывает сверху) и делитесь этой статьёй в Соц. сетях!

Источник

Автодополнение SQL кода прямо в редакторе PHPStorm

В PHPStorm есть встроенная возможность подключения автодополнения имен таблиц и полей в редакторе кода, однако не все об этом знают.

Если у вас код отображается примерно так, то прошу под кат.

Шаг 1. Подключение базы данных

Устанавливаем курсор в область SQL кода, у меня она выделена красным, и нажимаем Alt+Enter. Выбираем Configure Data Source

В открывшемся окошке выбираем JDBC драйвер, в данном случае MySQL, и, если нужно, нажимаем Click here. Выбираем какую-нибудь папку, где хотим разместить файлы, и нажимаем OK.

После того как шторм скачает драйвер, выбираем JDBC driver class.
В поле Database URL выбираем шаблон и меняем настройки на ваши, также указываем имя пользователя и пароль.

Если все сделали правильно, после нажатия на кнопку Test Connection появится подобное окошко.

Шаг 2. Выбираем SQL Dialects

SQL код в редакторе все еще красный. Бежим в настройки.
FileSettingsSQL Dialects
Напротив папки или отдельного файла нажимаем на keywords only и выбираем MySQL.
Теперь код в редакторе поменял цвет, и даже наверняка подсветились используемые поля, однако автодополнения все еще нет, точнее оно есть, но там нет ни полей, ни таблиц.

READ  Как подключить наушники через блютуз к телефону samsung galaxy

Шаг 3. Добавляем автодополнение

В данном случае этот шаг дела вкуса. Возможно вы не захотите автодополнения полей прямо в редакторе, ведь вы можете редактировать отдельно SQL код.
Для этого установите курсор в область SQL кода, нажмите Alt+Enter и выберите нечто вроде Edit MySQL fragment. В открытой области будет автодополнение полей и таблиц.

Но если вы все-таки решили не останавливаться, то устанавливаем курсор в SQL код, нажимаем Alt+Enter и выбираем Language Injection Settings.
В появившемся окошке щелкаем по php: «SQL select/delete/insert/update/create» и выбираем MySQL.

Все! Должно работать. Еще советую нажать в автодополнении на букву А в нижнем правом углу, если у вас там она, и переключиться на Sort by relevance.

UDP.
Пользователь Ramzeska подсказывает, что последний шаг можно выполнить зайдя в настройки проекта
«Language Inspections» => «PHP SQL select/delete. » ( в выпадающем меню попап-окна надо выбрать MySQL)

Источник

Database connection

To issue a query to a database, you must create a data source connection. Data source is the location of your data and can be a server or a DDL file. The data source includes a name and connection settings that are dependent on the data source type.

Amazon Redshift

At the bottom of the data source settings area, click the Download missing driver files link. Alternatively, you can specify user drivers for the data source. For more information about user drivers, see Add a user driver to an existing connection.

From the Connection type list, select a type of connection that you want to use:

URL only : connect by using the JDBC URL that you can copy in settings of your Amazon Redshift cluster.

From the Authentication list, select an authentication method.

pgpass : by using the PGPASS file. You can store this file in the user’s home directory (for example, /Users/jetbrains/.pgpass ).

User & Password : by using your login and password.

AWS profile : by using a named profile. A named profile is a collection of settings and credentials that you can use for authentication. Named profiles are stored in CREDENTIALS files. Default directories for these files are

/.aws/credentials (Linux and macOS) and %USERPROFILE%\.aws\credentials (Windows).

In your Redshift dashboard, create a Redshift cluster.

For more information about the Amazon Redshift cluster, read Getting Started with Amazon Redshift.

Paste the JDBC URL from the Redshift cluster settings to the URL field in PhpStorm.

In User and Password fields, specify your Redshift credentials.

Apache Cassandra

At the bottom of the data source settings area, click the Download missing driver files link. Alternatively, you can specify user drivers for the data source. For more information about user drivers, see Add a user driver to an existing connection.

Specify database connection details. Alternatively, paste the JDBC URL in the URL field.

If you want to configure an SSL connection to Apache Cassandra, see https://www.jetbrains.com/help/datagrip/how-to-connect-to-cassandra-with-ssl.html in the DataGrip documentation.

Apache Derby

At the bottom of the data source settings area, click the Download missing driver files link. Alternatively, you can specify user drivers for the data source. For more information about user drivers, see Add a user driver to an existing connection.

Specify database connection details. Alternatively, paste the JDBC URL in the URL field.

Apache Hive

At the bottom of the data source settings area, click the Download missing driver files link. Alternatively, you can specify user drivers for the data source. For more information about user drivers, see Add a user driver to an existing connection.

Specify database connection details. Alternatively, paste the JDBC URL in the URL field.

Azure SQL Database

In your Microsoft Azure account, create an SQL data source. For more information about the Azure SQL Database, read Azure SQL Database Documentation.

At the bottom of the data source settings area, click the Download missing driver files link.

Specify database connection details. Alternatively, paste the JDBC URL in the URL field.

Note : the Use Windows domain authentication checkbox is available only on Windows.

ClickHouse

At the bottom of the data source settings area, click the Download missing driver files link. Alternatively, you can specify user drivers for the data source. For more information about user drivers, see Add a user driver to an existing connection.

Specify database connection details. Alternatively, paste the JDBC URL in the URL field.

Exasol

At the bottom of the data source settings area, click the Download missing driver files link. Alternatively, you can specify user drivers for the data source. For more information about user drivers, see Add a user driver to an existing connection.

Specify database connection details. Alternatively, paste the JDBC URL in the URL field.

Greenplum

At the bottom of the data source settings area, click the Download missing driver files link. Alternatively, you can specify user drivers for the data source. For more information about user drivers, see Add a user driver to an existing connection.

READ  Как подключить шрифты к сайту html

Specify database connection details. Alternatively, paste the JDBC URL in the URL field.

At the bottom of the data source settings area, click the Download missing driver files link. Alternatively, you can specify user drivers for the data source. For more information about user drivers, see Add a user driver to an existing connection.

Specify database connection details. Alternatively, paste the JDBC URL in the URL field.

You can select between different H2 connection modes: Remote, In-memory, Embedded. For more information about these modes, see the official H2 documentation.

HSQLDB

At the bottom of the data source settings area, click the Download missing driver files link. Alternatively, you can specify user drivers for the data source. For more information about user drivers, see Add a user driver to an existing connection.

Specify database connection details. Alternatively, paste the JDBC URL in the URL field.

IBM Db2

At the bottom of the data source settings area, click the Download missing driver files link. Alternatively, you can specify user drivers for the data source. For more information about user drivers, see Add a user driver to an existing connection.

Specify database connection details. Alternatively, paste the JDBC URL in the URL field.

MariaDB

At the bottom of the data source settings area, click the Download missing driver files link. Alternatively, you can specify user drivers for the data source. For more information about user drivers, see Add a user driver to an existing connection.

Specify database connection details. Alternatively, paste the JDBC URL in the URL field.

Microsoft SQL Server

At the bottom of the data source settings area, click the Download missing driver files link. Alternatively, you can specify user drivers for the data source. For more information about user drivers, see Add a user driver to an existing connection.

Specify database connection details. Alternatively, paste the JDBC URL in the URL field.

The Instance field is optional.

If your TCP/IP connection to the host has failed, consider enabling TCP/IP in the SQL Server Network Configuration. For more information about configuring Microsoft SQL Server, Windows domain authentication, and user permissions, see How to connect to MS SQL server in the DataGrip documentation.

For more information about connecting to LocalDB, see How to connect to SQL Server Express LocalDB in the DataGrip documentation.

MongoDB

In MongoDB, for authentication, you must provide a username, password, and the authentication database that is associated with this username. If the authentication database differs from the database to which you want to connect, specify the authentication database with the authSource parameter in the URL. If no authentication database is specified, MongoDB uses the admin database by default.

At the bottom of the data source settings area, click the Download missing driver files link. Alternatively, you can specify user drivers for the data source. For more information about user drivers, see Add a user driver to an existing connection.

From the Connection type list, select your connection type:

default : standard connection string format (for example, mongodb://localhost:27021/admin ). Read more about standard connection string format in Standard Connection String Format at docs.mongodb.com.

MongoDB Atlas (SRV protocol) : DNS seedlist connection format (for example, mongodb+srv://unit1.test.net:27121,unit2.test.com:27021 ). Read more about standard connection string format in DNS Seedlist Connection Format at docs.mongodb.com.

MySQL

At the bottom of the data source settings area, click the Download missing driver files link. Alternatively, you can specify user drivers for the data source. For more information about user drivers, see Add a user driver to an existing connection.

Specify database connection details. Alternatively, paste the JDBC URL in the URL field.

Oracle

At the bottom of the data source settings area, click the Download missing driver files link.

From the Connection Type list, select a connection type:

SID : to use a unique name of an Oracle instance (a process that runs on the workstation).

Service name : to use an alias to an Oracle instance (or many instances).

URL only : to use the JDBC URL.

Specify database connection details. Alternatively, paste the JDBC URL in the URL field.

From the Driver list, specify the driver type. For more information about driver types, see Oracle JDBC FAQ.

At the bottom of the data source settings area, click the Download missing driver files link. Alternatively, you can specify user drivers for the data source. For more information about user drivers, see Add a user driver to an existing connection.

PostgreSQL

At the bottom of the data source settings area, click the Download missing driver files link. Alternatively, you can specify user drivers for the data source. For more information about user drivers, see Add a user driver to an existing connection.

READ  Как подключить субтитры в смартфоне

Specify database connection details. Alternatively, paste the JDBC URL in the URL field.

Snowflake

At the bottom of the data source settings area, click the Download missing driver files link. Alternatively, you can specify user drivers for the data source. For more information about user drivers, see Add a user driver to an existing connection.

Specify database connection details. Alternatively, paste the JDBC URL in the URL field.

Warehouse is a cluster of compute resources in Snowflake. A warehouse provides the required resources, such as CPU, memory, and temporary storage. For more information about Snowflake, see the Snowflake user guide.

SQLite

At the bottom of the data source settings area, click the Download missing driver files link. Alternatively, you can specify user drivers for the data source. For more information about user drivers, see Add a user driver to an existing connection.

To connect to an existing SQLite database, specify a file path to the database file in the File field.

Sybase ASE

At the bottom of the data source settings area, click the Download missing driver files link. Alternatively, you can specify user drivers for the data source. For more information about user drivers, see Add a user driver to an existing connection.

Specify database connection details. Alternatively, paste the JDBC URL in the URL field.

Vertica

At the bottom of the data source settings area, click the Download missing driver files link. Alternatively, you can specify user drivers for the data source. For more information about user drivers, see Add a user driver to an existing connection.

Specify database connection details. Alternatively, paste the JDBC URL in the URL field.

Other

Currently, PhpStorm supports vendors that are mentioned previously. The support includes such features as enhanced code completion and better retrieval of database objects (introspection). If your vendor is not in the list, you still can connect to the database with a JDBC driver.

Create a connection to a database with a JDBC driver

If you cannot find a name of a database vendor in the list of data sources, download a JDBC driver for the database management system (DBMS), and create a connection in PhpStorm. With the JDBC driver, you can connect to DBMS and start working.

Click the User Driver link.

In the Class field, specify the value that you want to use for the driver.

Return to the created data source connection.

Specify database connection details. Alternatively, paste the JDBC URL in the URL field.

If you connect to the vendor that is not in the list of supported data sources, PhpStorm uses JDBC metadata for database object retrieval (introspection) and the Generic SQL dialect. The introspection with JDBC metadata means that some specific database objects will not appear in the database tree view. For example, user-defined types (Apache Cassandra), macros (Apache Hive), extensions (PostgreSQL). With the Generic SQL dialect, you will have basic code completion like SELECT * FROM , but code completion will not include objects that were not retrieved during introspection.

Specify a library path for a driver

To work properly, some JDBC drivers require a path to library files along with the driver.

For example, to determine if the application should operate in the Instant Client mode, Oracle Instant Client (OCI) applications look for library files in the runtime library search path ( LD_LIBRARY_PATH on Linux or PATH on Windows). You can set these paths in the Data Sources and Drivers dialog.

In the Data Sources and Drivers dialog, click the driver entry to which you want to add a path to library files.

(Optional) Add a driver with which you want to work. For more information about adding a driver, see Create a connection to a database with a JDBC driver.

Navigate to the folder with library files. Ensure that the driver version corresponds to the version of these library files. For example, if you use the driver version 19.6, the attached library files must also have the 19.6 version.

DDL data source

SQL files that contain data definition language statements (DDL statements) can be used as data sources. As a result, you can reference all tables, columns and other objects defined in such files in the editor.

In the SQL Dialects dialog, select a dialect that you want to use for the added SQL file.

Productivity tips

Create a data source from the JDBC URL

In the URL field, paste the JDBC URL.

From the Driver list, select the necessary driver for the data source.

In the Data Sources and Drivers dialog, enter credentials.

Источник

Как подключить и установить...
Adblock
detector