750 likes | 1.4k Views
Creating D atabases with MySQL Workbench. Build the Forums database in Ullman’s Chapter 6. Download MySQL with mysql client. Download MySQL installer from: http ://dev.mysql.com/downloads / Go through the installation and set your password (make it short!)
E N D
Creating Databases with MySQL Workbench Build the Forums database in Ullman’s Chapter 6
Download MySQL with mysql client • Download MySQL installer from: http://dev.mysql.com/downloads/ • Go through the installation and set your password (make it short!) • Search, on your computer, for the MySQL Command Line client (e.g., Version 6.7) which is created with the installation of the MySQL • Put a copy of the short cut to the MySQL command line on your desktop or better, pin the shortcut to the taskbar for easy access
Start MySQL Command Line • Click the MySQL command line icon to start it • It will prompt you for entering the password which you set during installation. • You will get the mysql> prompt in the command line • Select the database you want to use: mysql> USE test; • Quit MySQL by typing the following in the command line: mysql> exit or: mysql> quit
Download MySQL Workbench • The MySQL workbench is a database management tool and a MYSQL server • It is available for PC, Mac, and Linux • Download a version of the Workbench for your computer from: http://dev.mysql.com/downloads/tools/workbench/ • Run and install the complete version as a developer • Accept all defaults and assign a short password • Put the shortcut on your computer or pin it to task bar • Click the icon to start it, enter your password
mysql client vs. MySQL Workbench • Note: You can either use the mysql command line or MySQL Workbench for SQL statements • The Workbench is much easier to use • Read Chapter 4 Ullman for learning how to use the mysql command line to communicate with a MySQL server • Read Chapter 5 Ullman to learn how to actually build a database, which you can do with the MySQL Workbench
MySQL Workbench • MySQL has a graphic interface for writing SQL statements, which is more convenient than the command line interface of the mysql client. • MySQL Workbench is used by professionals for designing, building, and managing databases • After installing it, click on Workbench’s icon to start it, and click on the “local instance MySQL 5.7” button • Note: your version may be different!) • Create a new connection to the server instance • Enter server details by typing parameters (hostname: 127.0.0.1; Port: 2206; Username: root) • Test it (needs password)! • Choose a short password (e.g., rock); you will enter it frequently!
Workbench Modules • Workbench has 3 modules for doing the following: • SQL Development • For working with queries, table data, and scripts • Data Modeling • For designing database and diagrams • Server Administration • For monitoring and configuring servers
SQL Development • Start the MySQL Workbench by clicking on its icon on your desktop > Home (i.e., click on the Home icon at the upper left corner of the page • Click on the connection that you created • Workbench detects if you have MySQL on your local system and creates a connection if you have it
Open a SQL Editor tab • The application opens on the connections tab • The SQL editor has four white areas (panes): • The top Query pane for typing and executing queries • The right SQL Additions pane for containing SQL statements • The bottom Output pane • The left Object browser for displaying metadata • You can close or extend the size of these panes with the 3 blue square icons on the upper right
Execute Queries • Queries are executed against a default database • Databases may be listed in the Navigator area in the left pane • > Right click a database (e.g., Sakila) • Select it as the default database by double clicking it • // now you are connected to Sakila database • In the top SQL pane, execute SQL statements against the database • Keywords are highlighted as you type in the pane. For example: select count(*) from customer;// see the results in Results pane • Do not forget the semicolon at the end, also no space between count and (*) • Execute (all or current) statement(s): > Query > Execute// or use the icons on the tool bar to execute the query
Set your ‘Preferences’ • You can capitalize keywords: > Edit > Preference > SQL Editor // Try the following query: SELECT avg(amount) FROM payment; • See the results in Results pane
Forward and Reverse Engineering • We can reverse or forward engineer an existing database (e.g., Sakila) > database > reverse engineer // then select a database • This creates a model of an existing database • We can arrange the diagrams with the Arrange menu item • Having a model, forward engineer it: > database > forward engineer • This creates the SQL statements (DDL) for database
Making a New Database • Start the workbench • Click on your Connection > File > New Model • Right click the default ‘mydb’ name > Edit Schema to edit the name of the new schema (database) • For example, change it to users; accept the defaults (by clicking “Next”) • This new database will show up under Navigator
Add a Table • Double click on “Add Table” • It adds a new table labeled by default as “table1”; Right click it to modify its name • Right click > Edit Table, and then create columns (attributes) for the table • Add column name, datatype, etc., for each attribute • Metaproperties: P (PK), N (NOT NULL), U (unique index), B (is binary column), U (unsigned datatype), Z (fill 0000 values if numeric), AI (auto increment), and Default • Alternatively, we can add a table graphically: • instead of > Add Table), click on: Add Diagram Double click the Add Diagram icon to start Add attributes …
Let’s Create user Table in the users Database Build the user table defined below in the Users database using MySQL Workbench: NOTE: The user table was designed in Chapter 4 in Ullman’s book! > File > New Model Click on mydb > Edit Schema and change the ‘mydb’ default name to “users” Double click the Add Table or Add Diagram to define the table (see previous slide) Let’s click on Add Diagram, and click the table icon and put it on the drawing area Right click ‘table1’. Create the user table and its columns from the model below: user_idMEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT, first_nameVARCHAR(20) NOT NULL, last_nameVARCHAR(40) NOT NULL, email VARCHAR(60) NOT NULL, pass CHAR(40) NOT NULL, registration_dateDATETIME NOT NULL, PRIMARY KEY (user_id), > File > Save Model AS … in your directory. Save the diagram > File > Export as PNG or jpeg, etc., file in a directory
The SQL for the user table will look like the following after forward engineering > Database > Forward Engineer // accept all defaults: CREATE TABLE IF NOT EXISTS `users`.`user` ( `user_id` MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT, `first_name` VARCHAR(20) NOT NULL, `last_name` VARCHAR(40) NOT NULL, `email` VARCHAR(60) NOT NULL, `pass` CHAR(40) NOT NULL, `registration_date` DATETIME NOT NULL, PRIMARY KEY (`user_id`) ) ENGINE = InnoDB;
Relating Two Tables • If you have a previously created table (e.g., user in the users database) (visible in the browser pane) drag it on the diagram pane next to the new table • > File > Open Model // open a database • If the table does not have Pk, make Pk for the tables to be related. • Select the source table, using the arrow “select object” at the top of the left tool bar • Click on the type of relationship (e.g., 1:m) from the left tool bar • Hold the ctrl key, and then click on the target table • Right click on the relationship > Edit relationship • Click on the Foreign key tab below to assign an FK • You can now forward engineer > database > forward engineer to get the data definition language (DDL) statements for the diagram (model) • Save the database in your folder • Next time you start your workbench, the database will be available > File >Open Model
Edit tables • We can edit existing tables of an existing database by right clicking the table, then > Edit Table • For example, you can change the color of the diagram and metadata of each table by clicking on the diagram, and then changing the color, etc., in the Properties Editor in the left browser pane
Object Browser • Shows the available databases (Sakila and your own databases) and their structural content: e.g., tables • You can view the instance data for each column of each database by right clicking it and then > select rows • You can also see the data for the whole table by right clicking it and then > select rows • You can also select a table and then directly write select, update, insert, and other SQL statements and send them to the SQL editor
Let’s practice SQL with Sakila • The existing Sakila database is great for practicing all kinds of SQL statements and queries • Start MySQL Workbench > Home • You should see Sakila among other databases that you have in the browser pane on the left • Click Sakila, and click Tables, and click on a table of your choice, for example: Customers • Right click the table • Note that you have so many options. Try: > Select Rows This shows you the records in the Customer table Try other options
Build the Forums database • Purpose: Build a message board where users can post their messages for other users to reply • Each user needs to register and then login with a combination of an email and password • Different subjects (topics) may have many forums • The final version of the Forums database, satisfying the 3NF, is shown on Figure 178, Chapter 6 of Ullman’s textbook • Let’s use it for our design!
Build Forums DB with MYSQL Workbench • Start the MySQL Workbench • Create a new connection • > New Model • Right click on mydb, then > Edit Schema; change name to Forums • Double click on Add Diagram • Use the ERD (entity relationship diagram) on page 178 of Ullman’s book as a guide, and start making the three tables of the Forums database
… • Click on the ‘Place a new Table’ and click on the drawing area • Right click ‘table1’ and then click on ‘Edit Table’ • Change the table name to users • Change column name and data types using the ERD on page 178 as a guide • Select any of the options: P: PK; N: NOT NULL; U: unique index; U: unsigned; AI: Auto-increment for each column • Repeat the process for the messages and forums tables of the database • Make sure to make all the Ids unique and index them as PK
Add indexes other than PK • Indexes are used for column that are frequently used in WHERE, ORDER BY, and JOINs • Do not index columns that can be NULL or have a narrow range of values such as Boolean (Y/N or 1/0) • Since users will login with a combination of their password and email address in the Forums database, we need to index the combination • This index will be used in SELECT clauses • We may also need to order the forums by their date-enteredIf so, we need to index it //This index will be used in ORDER BY clauses • Add indexes for columns frequently used in joins • Foreign keys are good candidates • Make sure to make any attribute (column) unique if you do not want its value duplicated in the table (See Table 6.6, page 181 Ullman’s book)
Types of Indexes • There are four types of indexes • INDEX //standard index is added to columns used in WHERE clauses, e.g., the combination of password and email columns • Or in ORDER BY clauses . For example, messiges.date_entered • Or in JOINS. This includes all foreign keys • UNIQUE // For columns whose values are not duplicated in the table • FULLTEXT // • PRIMARY KEY (special kind of UNIQUE) // Each table should have one • We can define the indexes when tables are created INDEX-TYPE index_name (columns) // index _name is optional, if not provided, it takes the column name: PRIMARY KEY (user_id) INDEXfull_name (last_name, first_name) NOTE: KEY is synonymous with INDEX in MySQL
Create Indexes in Workbench > Home > Open Model • Open the Forums database • Right click a table (e.g., messages) > Edit Table • At the bottom of the Results pane, a few tabs show up (Tables, Indexes, Foreign Keys, Triggers, …) • Click on the Indexes tab for that table • Add a new index at the bottom of the indexes, give it a name and type and select column • NOTE: For combination indexes (made of more than one column) just check the columns under the Index column for the tables under the Indexes tab
Open the database > Home > Open Model • Open the database • Now you see the Forums database along with other databases in the browser pane • You can now populate the database with values • See next slides • Click on Forums, and open the tables • Right click on a table (e.g., users)
Storage Engine for tables • MyISAM • Good if a table uses FULLTEXT (e.g., messages) • InnoDB • If table supports transaction, use this engine • This is the default engine in MySQL now • Is faster than MyISAM • Use this for the users and forums table
Populating a table • The syntax for the SQL clauses can be found in the SQL addition pane • Type: insert, and you will get the syntax for the INSERT clauses • Now you can use the clauses to insert values into a given table
Populating the table … • Write the INSERT statements in the SQL editor pane at the top • When we want only to enter values for certain columns: INSERT INTOtablename (column1, column2, …) VALUES (value1, value2, …); // Columns not given a value will get NULL unless they have a default // value. If they are NOT NULL and have no default there will be an error • When we want to enter values for all columns use the following: INSERT INTOtablenameVALUES (value1, NULL, value2, value3, …)
Populate the users Table • Start Workbench • Click on myConnection • You will see the database in object browser on the left • Right click a table of a database • Right click ‘columns’ in that table • > Send to SQL Editor > Insert statement • Use the statement below to insert values INSERT INTO users (user_id, username, pass, first_name, last_name, email) VALUES ('1', 'rock', SHA1('gneiss'), 'Hassam', 'Babaie', 'mylonite_7@yahoo.com') Result: 1 row(s) affected 0.000 sec Repeat this for other users …
See the Populated Table • Right click the table • > Select rows • You see the following: '1', 'rock', 'e6bd3229e0377a1d023b09d45fbfb91b17d2a021', 'Hassam', 'Babaie', 'mylonite_7@yahoo.com‘ Notice that the first name is misspelled! Right click the users table and > Select rows and correct it '1', 'rock', 'e6bd3229e0377a1d023b09d45fbfb91b17d2a021', 'Hassan', 'Babaie', 'mylonite_7@yahoo.com'