Это руководство нуждается в доработке. Вы можете отредактировать его на GitHub, следуя этим рекомендациям.

В этом документе показано, как настроить подключение к базе данных MySQL из среды IDE NetBeans. После подключения вы можете начать работать с MySQL в обозревателе баз данных среды IDE, создавая новые базы данных и таблицы, заполняя таблицы данными и выполняя SQL-запросы к структурам и содержимому базы данных. Это учебное пособие предназначено для начинающих, имеющих базовое представление об управлении базами данных, которые хотят применить свои знания для работы с MySQL в среде IDE NetBeans.

MySQL i- популярная система управления реляционными базами данных с открытым исходным кодом (СУБД), широко используемая в веб-приложениях благодаря своей скорости, гибкости и надежности. MySQL использует SQL, или Structured Query Language (язык структурированных запросов), для доступа к данным, содержащимся в базах данных, и их обработки.

  В этом руководстве предполагается, что на вашем компьютере уже установлена и настроена СУБД MySQL. Если вы выполняете установку впервые, пожалуйста, обратитесь за помощью к официальной документации по MySQL. Вы также можете обратиться к разделу Настройка сервера баз данных MySQL в операционной системе Windows.

Настройка свойств сервера MySQL

IDE NetBeans поставляется в комплекте с поддержкой СУБД MySQL. Прежде чем вы сможете получить доступ к серверу баз данных MySQL в IDE NetBeans, вы должны настроить свойства сервера MySQL.

  1. Щелкните правой кнопкой мыши узел "Базы данных" в окне "Службы" и выберите "Зарегистрировать сервер MySQL", чтобы открыть диалоговое окно "Свойства сервера MySQL".

mysql props1

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

Обратите внимание, что IDE вводит localhost в качестве имени узла сервера по умолчанию и 3306 в качестве номера порта сервера по умолчанию.

  1. Введите имя пользователя администратора (если оно не отображается).
  Вам необходим административный доступ, чтобы иметь возможность создавать и удалять базы данных.
  1. Введите пароль администратора. По умолчанию задано пустое значение.
  Пустой пароль также может быть паролем.
  1. Перейдите на вкладку "Свойства администратора" в верхней части диалогового окна.

Затем откроется вкладка "Свойства администратора", позволяющая ввести информацию для управления сервером MySQL.

  1. В поле Путь/URL к инструменту администрирования введите или перейдите к расположению вашего приложения для администрирования MySQL, такого как инструмент администрирования MySQL, phpMyAdmin или другие веб-инструменты администрирования.
  mysqladmin - это инструмент администрирования MySQL, который находится в папке bin каталога установки MySQL. Это инструмент командной строки, который не идеально подходит для использования с IDE.

Введите любые аргументы для инструмента администрирования в поле Аргументы.

  1. В поле Путь к команде запуска введите команду запуска MySQL или перейдите к ее расположению. Чтобы найти команду запуска, найдите mysqld в папке bin каталога установки MySQL.
  Рекомендуемый двоичный файл для Unix и NetWare - mysql_safe. Команда запуска также может отличаться, если MySQL был установлен в рамках установки AMP.

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

  1. В поле Путь к команде stop введите команду MySQL stop или перейдите к ее расположению. Обычно это путь к mysqladmin в папке bin каталога установки MySQL. Если используется команда mysqladmin, в поле "Аргументы" введите -u root stop, чтобы предоставить права суперпользователя на остановку сервера.
  2. Когда вы закончите, вкладка "Свойства администратора" должна выглядеть так, как показано на следующем рисунке. Если вы удовлетворены своей конфигурацией, нажмите "ОК".

mysql props2

Запуск сервера MySQL

Прежде чем вы сможете подключиться к серверу баз данных MySQL, вы должны сначала убедиться, что сервер баз данных MySQL запущен на вашем компьютере. Если сервер базы данных не подключен, вы увидите (отключен) рядом с именем пользователя в узле сервера MySQL в окне обслуживания, и вы не сможете развернуть этот узел.

Чтобы подключиться к серверу баз данных, убедитесь, что сервер баз данных MySQL запущен на вашем компьютере, щелкните правой кнопкой мыши узел базы данных > Сервер MySQL в окне "Службы" и выберите "Подключиться". Возможно, вам будет предложено ввести пароль для подключения к серверу.

services running

When the server is connected you will be able to expand the MySQL Server node and view the all available MySQL databases.

Creating and Connecting to the Database Instance

A common way of interacting with databases is through an SQL editor. NetBeans IDE has a built-in SQL Editor for this purpose. The SQL Editor is generally accessible via the Execute Command option from the right-click menu of the connection node (or of the connection node’s child nodes). Now that you are connected to the MySQL server, you can create a new database instance using the SQL Editor. For purposes of this tutorial, create an instance called MyNewDatabase :

  1. In the IDE’s Services window, right-click the MySQL Server node and choose Create Database.

The Create MySQL Database dialog box opens.

  1. In the Create MySQL Database dialog box, type the name of the new database. We will use MyNewDatabase for this tutorial. Leave the checkbox unselected at this time.

create db dbx

  You can also grant full access to a given user. By default, only the admin user has the permissions to perform certain commands. The drop down list lets you assign these permissions to a specified user.
  1. Click OK.

The new database appears under the MySQL Server node in the Services window.

  1. Right-click the new database node and choose Connect in the popup menu to open the connection to the database.

Database connections that are open are represented by a complete connection node (connection node icon) in the Services window.

Creating Database Tables

Now that you have connected to MyNewDatabase , you can begin exploring how to create tables, populate them with data, and modify data maintained in tables. This allows you to take a closer look at the functionality offered by the Database Explorer, as well as NetBeans IDE’s support for SQL files.

``MyNewDatabase`` is currently empty. In the IDE it is possible to add a database table by either using the Create Table dialog, or by inputting an SQL query and running it directly from the SQL Editor. In the following exercises you will use the SQL editor to create the `Counselor` table and the Create Table dialog box to create the `Subject` table. After you create the tables you will run an SQL script to populate the tables.

  1. Using the SQL Editor
  2. Using the Create Table Dialog

Using the SQL Editor

In this exercise you will use the SQL editor to create the Counselor table.

  1. In the Database Explorer, expand the MyNewDatabase connection node (connection node icon) and note that there are three subfolders: Tables, Views and Procedures.
  2. Right-click the Tables folder and choose Execute Command. A blank canvas opens in the SQL Editor in the main window.
  3. In the SQL Editor, type in the following query. This is a table definition for the Counselor table you are about to create.

CREATE TABLE Counselor ( id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT, firstName VARCHAR (50), nickName VARCHAR (50), lastName VARCHAR (50), telephone VARCHAR (25), email VARCHAR (50), memberSince DATE DEFAULT '0000-00-00', PRIMARY KEY (id) );

  Queries formed in the SQL Editor are parsed in Structured Query Language (SQL). SQL adheres to strict syntax rules which you should be familiar with when working in the IDE’s Editor. Upon running a query, feedback from the SQL engine is generated in the Output window indicating whether execution was successful or not.
  1. To execute the query, either click the Run SQL (run sql button) button in the task bar at the top (Ctrl-Shift-E), or right-click within the SQL Editor and choose Run Statement. The IDE generates the Counselor table in the database, and you receive a message similar to the following in the Output window.

create counselor query

  1. To verify changes, right-click the Tables node in the Database Explorer and choose Refresh. The Refresh option updates the Database Explorer’s UI component to the current status of the specified database. Note that the new Counselor table node (table node) now displays under Tables in the Database explorer. If you expand the table node you can see the columns (fields) you created, starting with the primary key (primary key icon).

counselor table

Using the Create Table Dialog

In this exercise you will use the Create Table dialog box to create the Subject table.

  1. In the Database Explorer, right-click the Tables node and choose Create Table. The Create Table dialog opens.
  2. In the Table name text field, type Subject .
  3. Click Add Column.
  4. For the Name of the column, enter id . Choose SMALLINT for data type from the Type drop-down list. Click OK.

add column dialog

  1. Select the Primary Key check box in the Add Column dialog box. You are specifying the primary key for your table. All tables found in relational databases must contain a primary key. Note that when you select the Key check box, the Index and Unique check boxes are also automatically selected and the Null check box is deselected. This is because primary keys are used to identify a unique row in the database, and by default form the table index. Because all rows need to be identified, primary keys cannot contain a Null value.
  2. Repeat this procedure by adding the remaining columns, as shown in the following table.
KeyIndexNullUniqueColumn NameData TypeSize

[checked]

[checked]

 

[checked]

id

SMALLINT

0

   

[checked]

 

name

VARCHAR

50

   

[checked]

 

description

VARCHAR

500

   

[checked]

 

FK_counselorID

SMALLINT

0

You are creating a table named Subject that will hold data for each of the following records.

  • Name: name of the subject
  • Description: description of the subject
  • Counselor ID: counselor ID that corresponds to an ID from the Counselor table

create table subject

Make sure that the fields in your Create Table dialog match those shown above, then click OK. The IDE generates the Subject table in the database, and you can see a new Subject table node (table node) immediately display under Tables in the Database Explorer.

Working with Table Data

In order to work with table data, you can make use of the SQL Editor in NetBeans IDE. By running SQL queries on a database, you can add, modify and delete data maintained in database structures. To add a new record (row) to the Counselor table, do the following:

  1. Choose Execute Command from the Tables folder in the Database Explorer. A blank canvas opens in the SQL Editor in the main window.
  2. In the SQL Editor, type in the following query.

INSERT INTO Counselor VALUES (1, 'Ricky', '"The Dragon"', 'Steamboat','334 612-5678', 'r_steamboat@ifpwafcad.com', '1996-01-01')

  1. To execute the query, right-click within the SQL Editor and choose Run Statement. In the Output window, you can see a message indicating that the query was successfully executed.
  2. To verify that the new record has been added to the Counselor table, in the Database Explorer, right-click the Counselor table node and choose View Data. A new SQL Editor pane opens in the main window. When you choose View Data, a query to select all the data from the table is automatically generated in the upper region of the SQL Editor. The results of the statement are displayed in a table view in the lower region. In this example, the Counselor table displays. Note that a new row has been added with the data you just supplied from the SQL query.

sql results

Running an SQL Script

Another way to manage table data in NetBeans IDE is by running an external SQL script directly in the IDE. If you have created an SQL script elsewhere, you can simply open it in NetBeans IDE and run it in the SQL Editor.

For demonstrative purposes, download ifpwafcad.sql and save it to a location on your computer. This script creates two tables similar to what you just created above ( Counselor and Subject ), and immediately populates them with data.

Because the script overwrites these tables if they already exist, delete the Counselor and Subject tables now so it becomes obvious that new tables are being created when the script is run. To delete tables:

  1. Right-click the Counselor and Subject table nodes in the Database Explorer and choose Delete.
  2. Click Yes in the Confirm Object Deletion dialog box. Note that the dialog box lists the tables that will be deleted.

When you click Yes in the Confirm Object Deletion dialog box, the table nodes are automatically removed from the Database Explorer.

To run the SQL script on MyNewDatabase :

  1. Choose File > Open File from the IDE’s main menu. In the file browser navigate to the location where you previously saved ifpwafcad.sql and click Open. The script automatically opens in the SQL Editor.
  2. Make sure your connection to MyNewDatabase is selected from the Connection drop-down box in the toolbar at the top of the Editor.

connection drop down

  1. Click the Run SQL (run sql button) button in the SQL Editor’s task bar. The script is executed against the selected database, and any feedback is generated in the Output window.
  2. To verify changes, right-click the MyNewDatabase connection node in the Runtime window and choose Refresh. The Refresh option updates the Database Explorer’s UI component to the current status of the specified database. Note that the two new tables from the SQL script now display as a table nodes under MyNewDatabase in the Database Explorer.
  3. Choose View Data from the right-click menu of a selected table node to see the data contained in the new tables. In this manner, you can compare the tabular data with the data contained in the SQL script to see that they match.

Conclusion

This concludes the Connecting to a MySQL Database tutorial. This document demonstrated how to configure MySQL on your computer and set up a connection to the database server from NetBeans IDE. It also described how to work with MySQL in the IDE’s Database Explorer by creating new database instances and tables, populating tables with data, and running SQL queries.