You are on page 1of 23

COLLEGE OF ENGINEERING, PANDHARPUR SE ENGINEERING LAB DATABA

TITLE: ER DIAGRAMS
AIM: Draw ER diagrams for any specific application & convert them into table . Descriptions: Introduction to ER Diagram An Entity Relationship Diagram (ERD) is a snapshot of data structures. ERDs show entities in a database and relationships between tables within that database. It is essential to have one of ERD if you want to create a good database design. The patterns help focus on how the database actually works with all of the interactions and data flows, although another useful tool is a Data Flow Diagram (DFD) which more directly describes this. An ERD facilitates visualizing relationship amongst tables by establishing linkages through a key in particular table pointing to specific records in the related tables.
Why use ER Diagrams ?

o Provides a global quick reference to an organizations data structures. o Can be used individually to design an Information Systems (IS) data structure o Can be used with Data Flow Diagrams to provide a more comprehensive IS logical design.
ERD Development Process

o Identify the entities o Determine the attributes for each entity o Select the primary key for each entity o Establish the relationships between the entities o Draw an entity model o Test the relationships and the keys o Attributes are characteristics that allow us to classify/describe an entity e.g., entity STUDENT has the attributes: student number, name, date of birth, course number

M.A.Dyade

COLLEGE OF ENGINEERING, PANDHARPUR SE ENGINEERING LAB DATABA

Summary of the ER diagram notation

Notation

Meaning
Entity type Attribute Key attribute Derived attribute Multivalued attribute Composite attribute Relationship type Total participation Many-to-one relationship Weak entity type with identifying relationship Identifying relationship type

M.A.Dyade

COLLEGE OF ENGINEERING, PANDHARPUR

COMPANY ER Schema Diagram Entity Types are: EMPLOYEE, DEPARTMENT, PROJECT, and DEPENDENT

SE ENGINEERING LAB

DATABA

Reduction of an E-R Schema to Tables Step 1: Mapping of Regular Entity Types Step 2: Mapping of Weak Entity Types Step 3: Mapping of Binary 1:1 Relation Types Step 4: Mapping of Binary 1:N Relationship Types. Step 5: Mapping of Binary M:N Relationship Types. Step 6: Mapping of Multivalued attributes. Step 7: Mapping of N-ary Relationship Types. Step 8: Options for Mapping Specialization or Generalization. Step 9: Mapping of Union Types (Categories).

M.A.Dyade

COLLEGE OF ENGINEERING, PANDHARPUR

Step 1: Mapping of Regular Entity Types. For each regular (strong) entity type E in the ER schema, create a relation R that includes all the simple attributes of E. Choose one of the key attributes of E as the primary key for R. If the chosen key of E is composite, the set of simple attributes that form it will together form the primary key of R. Example: We create the relations EMPLOYEE, DEPARTMENT, and PROJECT in the relational schema corresponding to the regular entities in the ER diagram. SSN, DNUMBER, and PNUMBER are the primary keys for the relations EMPLOYEE, DEPARTMENT, and PROJECT as shown. Step 2: Mapping of Weak Entity Types For each weak entity type W in the ER schema with owner entity type E, create a relation R and include all simple attributes (or simple components of composite attributes) of W as attributes of R. In addition, include as foreign key attributes of R the primary key attribute(s) of the relation(s) that correspond to the owner entity type(s). The primary key of R is the combination of the primary key(s) of the owner(s) and the partial key of the weak entity type W, if any. Example: Create the relation DEPENDENT in this step to correspond to the weak entity type DEPENDENT. Include the primary key SSN of the EMPLOYEE relation as a foreign key attribute of DEPENDENT (renamed to ESSN). The primary key of the DEPENDENT relation is the combination {ESSN, DEPENDENT_NAME} because DEPENDENT_NAME is the partial key of DEPENDENT.

SE ENGINEERING LAB

DATABA

M.A.Dyade

COLLEGE OF ENGINEERING, PANDHARPUR

Step 3: Mapping of Binary 1:1 Relation Types For each binary 1:1 relationship type R in the ER schema, identify the relations S and T that correspond to the entity types participating in R. There are three possible approaches: (1) Foreign Key approach: Choose one of the relations-S, say-and include a foreign key in S the primary key of T. It is better to choose an entity type with total participation in R in the role of S. Example: 1:1 relation MANAGES is mapped by choosing the participating entity type DEPARTMENT to serve in the role of S, because its participation in the MANAGES relationship type is total. (2) Merged relation option: An alternate mapping of a 1:1 relationship type is possible by merging the two entity types and the relationship into a single relation. This may be appropriate when both participations are total. (3) Cross-reference or relationship relation option: The third alternative is to set up a third relation R for the purpose of cross-referencing the primary keys of the two relations S and T representing the entity types.

SE ENGINEERING LAB

DATABA

Step 4: Mapping of Binary 1:N Relationship Types. For each regular binary 1:N relationship type R, identify the relation S that represent the participating entity type at the N-side of the relationship type. Include as foreign key in S the primary key of the relation T that represents the other entity type participating in R. Include any simple attributes of the 1:N relation type as attributes of S.

M.A.Dyade

COLLEGE OF ENGINEERING, PANDHARPUR

Example: 1:N relationship types WORKS_FOR, CONTROLS, and SUPERVISION in the figure. For WORKS_FOR we include the primary key DNUMBER of the DEPARTMENT relation as foreign key in the EMPLOYEE relation and call it DNO. Step 5: Mapping of Binary M:N Relationship Types. For each regular binary M:N relationship type R, create a new relation S to represent R. Include as foreign key attributes in S the primary keys of the relations that represent the participating entity types; their combination will form the primary key of S. Also include any simple attributes of the M:N relationship type (or simple components of composite attributes) as attributes of S. Example: The M:N relationship type WORKS_ON from the ER diagram is mapped by creating a relation WORKS_ON in the relational database schema. The primary keys of the PROJECT and EMPLOYEE relations are included as foreign keys in WORKS_ON and renamed PNO and ESSN, respectively. Attribute HOURS in WORKS_ON represents the HOURS attribute of the relation type. The primary key of the WORKS_ON relation is the combination of the foreign key attributes {ESSN, PNO}. Step 6: Mapping of Multivalued attributes. For each multivalued attribute A, create a new relation R. This relation R will include an attribute corresponding to A, plus the primary key attribute K-as a foreign key in R-of the relation that represents the entity type of relationship type that has A as an attribute. The primary key of R is the combination of A and K. If the multivalued attribute is composite, we include its simple components. Example: The relation DEPT_LOCATIONS is created. The attribute DLOCATION represents the multivalued attribute LOCATIONS of DEPARTMENT, while 6 M.A.Dyade

SE ENGINEERING LAB

DATABA

COLLEGE OF ENGINEERING, PANDHARPUR

DNUMBER-as foreign key-represents the primary key of the DEPARTMENT relation. The primary key of R is the combination of {DNUMBER, DLOCATION}. Step 7: Mapping of N-ary Relationship Types. For each n-ary relationship type R, where n>2, create a new relationship S to represent R. Include as foreign key attributes in S the primary keys of the relations that represent the participating entity types. Also include any simple attributes of the n-ary relationship type (or simple components of composite attributes) as attributes of S. Example: The relationship type SUPPY in the ER below. This can be mapped to the relation SUPPLY shown in the relational schema, whose primary key is the combination of the three foreign keys {SNAME, PARTNO, PROJNAME}

SE ENGINEERING LAB

DATABA

Summary of Mapping constructs and constraints ER Model Entity type 1:1 or 1:N relationship type M:N relationship type n-ary relationship type Simple attribute Composite attribute Multivalued attribute Value set Key attribute Relational Model Entity relation Foreign key (or relationship relation) Relationship relation and two foreign keys Relationship relation and n foreign keys Attribute Set of simple component attributes Relation and foreign key Domain Primary (or secondary) key

M.A.Dyade

COLLEGE OF ENGINEERING, PANDHARPUR SE ENGINEERING LAB DATABA

M.A.Dyade

COLLEGE OF ENGINEERING, PANDHARPUR

Mapping the COMPANY ER schema into a Relational schema. o

SE ENGINEERING LAB

DATABA

M.A.Dyade

COLLEGE OF ENGINEERING, PANDHARPUR

Conclusion:

SE ENGINEERING LAB

DATABA

Several kinds of integrity constraints can be expressed in the ER model: key constraints,
participation constraints, and overlap/covering constraints for ISA hierarchies. Some foreign key constraints are also implicit in the definition of a relationship set. Some constraints (notably, functional dependencies) cannot be expressed in the ER model. Constraints play an important role in determining the best database design for an enterprise. ER design is subjective. There are often many ways to model a given scenario! Analyzing alternatives can be tricky, especially for a large enterprise. Common choices include: Entity vs. attribute, entity vs. relationship, binary or n-ary relationship, whether or not to use ISA hierarchies, and whether or not to use aggregation. Ensuring good database design: resulting relational schema should be analyzed and refined further. FD information and normalization techniques are especially useful.

M.A.Dyade

COLLEGE OF ENGINEERING, PANDHARPUR SE ENGINEERING LAB DATABA

ER DIAGRAM FOR A BANK DATABASE

OR

M.A.Dyade

COLLEGE OF ENGINEERING, PANDHARPUR SE ENGINEERING LAB DATABA

M.A.Dyade

COLLEGE OF ENGINEERING, PANDHARPUR

An ER diagram for an AIRLINE database schema

SE ENGINEERING LAB

DATABA

M.A.Dyade

COLLEGE OF ENGINEERING, PANDHARPUR SE ENGINEERING LAB DATABA

TITLE: Data Dictionary

AIM: To Create a tables, along with constraints and store them in a file, which will work as DD The data dictionary (also called system catalog) stores metadata -- data about data. For example: o Information about relations names of relations o Names and types of attributes of each relation o Names and definitions of views o Integrity constraints o User and account information, including passwords o Statistical and descriptive data o Number of tuples in each relation o Physical file organization information o How relation is stored (sequential, hash, clustered, etc.) o Physical location of relation -- operating system file name or disk addresses of blocks containing records of the relation o Information about indices o In effect, the data dictionary is a mini database. The data within can either be stored as: o Special-purpose data structures and code to access it, or o A set of relations, using the existing database structures and code to access it (most common solution)
Example of a possible system catalog representation:

o Relation-metadata =(relation-name, number-of-attributes,storage-organization,


location)

o Attribute-metadata =(attribute-name, relation-name, domain-type, position,


length)

o User-metadata =(user-name, encrypted-password, group) o Index-metadata =(index-name, relation-name, index-type,index-attributes) o View-metadata =(view-name, definition) The JDBC Driver Manager The JDBC Driver Manager is a very important class that defines objects which connect Java applications to a JDBC driver. The main responsibility of JDBC database driver is to load all the drivers found in the system properly as well as to select the most appropriate driver from opening a connection to a database. The Driver Manager also helps to select the most appropriate driver from the previously loaded drivers when a new open database is connected. The DriverManager class works between the user and the drivers. The task of the DriverManager class is to keep track of the drivers that are available and handles establishing a connection between a database and the appropriate driver. It even keeps track of the driver login time limits and printing of log and tracing messages. This class is 1 M.A.Dyade

COLLEGE OF ENGINEERING, PANDHARPUR

mainly useful for the simple application, the most frequently used method of this class is DriverManager.getConnetion(). The DriverManager class maintains the list of the Driver classes. Each driver has to be get registered in the DriverManager class by calling the method DriverManager.registerDriver(). The driver is loaded by calling the Class.forName() method. JDBC drivers are designed to tell the DriverManager about themselves automatically when their driver implementation class get loads. This class has many methods. Some of the commonly used methods are given below: deregisterDriver(Driver driver) : It drops the driver from the list of drivers registered in the DriverManager class. registerDriver(Driver driver) : It registers the driver with the DriverManager class. getConnection(String url) : It tries to establish the connection to a given database URL. getConnection(String url, Sting user, String password) : It tries to establish the connection to a given database URL. getConnection(String url, Properties info) : It tries to establish the connection to a given database URL. getDriver(String url) : It attempts to locate the driver by the given string. getDrivers() : It retrieves the enumeration of the drivers which has been registered with the DriverManager class Statement:It is a interface. Statement object executes the SQL statement and returns the result it produces. createStatement():It is a method of Connection interface. which returns Statement object. This method will compile again and again whenever the program runs. CREATE TABLE table_name(field_name):An appropriate code used for creating a table with given field name. executeUpdate(String table):This method also executes SQL statement that may be INSERT, UPDATE OR DELETE statement are used in the code. It takes string types parameters for SQL statement. It returns int.

SE ENGINEERING LAB

DATABA

Firstly we need to to establish the connection with the database. This is done by using the method DriverManager.getConnection(). This method takes a string containing a URL. The DriverManager class, attempts to locate a driver that can connect to the database represented by the string URL. Whenever the getConnection() method is called the DriverManager class checks the list of all registered Driver classes that can connect to the database specified in the URL.
Syntax:String url = "jdbc: odbc: makeConnection"; Connection con = DriverManager.getConnection(url, "userID", "password");

M.A.Dyade

COLLEGE OF ENGINEERING, PANDHARPUR

Program to establish the connection with database and creating a table with some fields. If table name already exists then we are displaying the message "Table already exists!".
import java.sql.*; public class CreateTable{ public static void main(String[] args) { System.out.println("Table Creation Example!"); Connection con = null; String url = "jdbc:mysql://localhost:3306/"; String dbName = "jdbctutorial"; String driverName = "com.mysql.jdbc.Driver"; String userName = "root"; String password = "root"; try{ Class.forName(driverName).newInstance(); con = DriverManager.getConnection(url+dbName, userName, password); try{ Statement st = con.createStatement(); String table = "CREATE TABLE Employee(Emp_code integer, Emp_name varchar(10))"; st.executeUpdate(table); System.out.println("Table creation process successfully!"); } catch(SQLException s){ System.out.println("Table all ready exists!"); } con.close(); } catch (Exception e){ e.printStackTrace(); } } }

SE ENGINEERING LAB

DATABA

M.A.Dyade

COLLEGE OF ENGINEERING, PANDHARPUR

Output:

SE ENGINEERING LAB

DATABA

M.A.Dyade

COLLEGE OF ENGINEERING, PANDHARPUR SE ENGINEERING LAB DATABA

Retrieving Tables from a Database


In database system it is very important to know about the tables. To work with this, it is very important to know how to retrieve a table and create a table in the database. This section provides you a facility for retrieving tables from a specific database through an example. In relational database, all the data is stored in the tabular format (rows and columns). See detail information below: Description of program: In this program we are establishing the connection between the MySQL database and Java file. We will retrieve the table with the help of some java methods and APIs interface. If the database has one or more tables then it shows all tables, otherwise displays the message "No any table in the database". Description of code: DatabaseMetaData: This is an interface of java.sql package that implemented by driver vendors. It tells about the data of the data like number of tables in the database , the information about the columns of the table. getMetaData(): It is a method of Connection interface. This method has metadata around the database and retrieves DatabaseMetaData object. ResultSet: The ResultSet is an interface that provides getter methods (getBoolean, getString, getTable and so on) for retrieving values. A ResultSet object is by default not updatable and forward only. getTables(null, null, "%", types): This method returns ResultSet and takes the following string types parameter: catalog : Table catalog name (may be null) schemaPattern : Table catalog name (may be null) tableNamePattern : Table name("%") types : Table type rs.next(): This method returns the next element of the ResultSet object. getString("Table name"): Above method retrieves the values from ResultSet object. It takes string type value. Here is the code of program: 1 M.A.Dyade

COLLEGE OF ENGINEERING, PANDHARPUR

import java.sql.*;

SE ENGINEERING LAB

DATABA

public class AllTableName{ public static void main(String[] args) { System.out.println("Listing all table name in Database!"); Connection con = null; String url = "jdbc:mysql://localhost:3306/"; String db = "jdbctutorial"; String driver = "com.mysql.jdbc.Driver"; String user = "root"; String pass = "root"; try{ Class.forName(driver); con = DriverManager.getConnection(url+db, user, pass); try{ DatabaseMetaData dbm = con.getMetaData(); String[] types = {"TABLE"}; ResultSet rs = dbm.getTables(null,null,"%",types); System.out.println("Table name:"); while (rs.next()){ String table = rs.getString("TABLE_NAME"); System.out.println(table); con.close(); } } catch (SQLException s){ System.out.println("No any table in the database"); } } catch (Exception e){ e.printStackTrace(); } } }

Output of program:
C:\vinod\jdbc\jdbc-mysql>javac AllTableName.java C:\vinod\jdbc\jdbc-mysql>java AllTableName Listing all table name in Database! Table name: employee employee11 employee2 employee3 employee4 employee5 employee6 employee8 employee9 java_datatypes java_datatypes2 javatypes

M.A.Dyade

COLLEGE OF ENGINEERING, PANDHARPUR

After making the table in the database, we need to insert the values in the database. Here we are going to see, how we can insert values in the MySQL database table.

SE ENGINEERING LAB

DATABA

Inserting values in MySQL database table


After making the table in the database, we need to insert the values in the database. Here we are going to see, how we can insert values in the MySQL database table. We know that tables store data in rows and column format. After creating a database table, you need to insert the values in it. In this section, we are providing an example with code that provides the facility for inserting the values in MySQL database table. Description of program: First of all this program establishes the connection with MySQL database through the JDBC driver, after only that we will be able to insert the values in specific table with the help of some APIs and methods. If any values get inserted in the table then shows a message "1 row affected" but if any problems comes while inserting the data in the table then it will displays the message "SQL statement is not executed!". Description of code: INSERT table_name VALUES(field_values): Above code is used, when you want to insert values in the database table with appropriate value. Here is the code of program:
import java.sql.*; public class InsertValues{ public static void main(String[] args) { System.out.println("Inserting values in Mysql database table!"); Connection con = null; String url = "jdbc:mysql://localhost:3306/"; String db = "jdbctutorial"; String driver = "com.mysql.jdbc.Driver"; try{ Class.forName(driver); con = DriverManager.getConnection(url+db,"root","root"); try{ Statement st = con.createStatement(); int val = st.executeUpdate("INSERT employee VALUES("+13+","+"'A man'"+")"); System.out.println("1 row affected"); } catch (SQLException s){ System.out.println("SQL statement is not executed!"); } }

M.A.Dyade

COLLEGE OF ENGINEERING, PANDHARPUR

} }

catch (Exception e){ e.printStackTrace(); }

SE ENGINEERING LAB

DATABA

Output of program: C:\vinod\jdbc\jdbc\jdbcmysql>javac InsertValues.java C:\vinod\jdbc\jdbc\jdbcmysql>java InsertValues Inserting values in Mysql database table! 1 row affected

M.A.Dyade

COLLEGE OF ENGINEERING, PANDHARPUR SE ENGINEERING LAB DATABA

Retrieving All Rows from a Database Table


Here, you will learn how to retrieve all rows from a database table. You know that table contains the data in rows and columns format.

Here, you will learn how to retrieve all rows from a database table. You know that table contains the data in rows and columns format. If you want to access the data from a table then you need to use some APIs and methods. See brief descriptions for retrieving all rows from a database table as below: Description of program: Program establishes the connection between MySQL database and java file so that the we can retrieve all data from a specific database table. If any exception occurs then shows a message "SQL code does not execute.". Description of code: executeQuery(String sql): This method executes the SQL statement and returns a single ResultSet object. It takes string type parameter for executing the SQL statement. SELECT * FROM table_name: Above code retrieves all data from specific database table. getInt(String column_name): This method is of java.sql.ResultSet interface that takes string type parameter and returns an integer type values. getString(String column_name): This method is same as getInt() method but it returns the string type values. Here is the code of program:
import java.sql.*; public class GetAllRows{ public static void main(String[] args) { System.out.println("Getting All Rows from a table!"); Connection con = null; String url = "jdbc:mysql://localhost:3306/"; String db = "jdbctutorial"; String driver = "com.mysql.jdbc.Driver"; String user = "root"; String pass = "root";

M.A.Dyade

COLLEGE OF ENGINEERING, PANDHARPUR

} }

try{ Class.forName(driver).newInstance(); con = DriverManager.getConnection(url+db, user, pass); try{ Statement st = con.createStatement(); ResultSet res = st.executeQuery("SELECT * FROM employee6"); System.out.println("Emp_code: " + "\t" + "Emp_name: "); while (res.next()) { int i = res.getInt("Emp_code"); String s = res.getString("Emp_name"); System.out.println(i + "\t\t" + s); } con.close(); } catch (SQLException s){ System.out.println("SQL code does not execute."); } } catch (Exception e){ e.printStackTrace(); }

SE ENGINEERING LAB

DATABA

Output of program:

C:\vinod\jdbc\jdbc-mysql>java GetAllRows Getting All Rows from a table! Emp_code: Emp_name: 10 vinod 11 Amar 15 Aman 1 sushil

http://www.2dix.com/ppt-2010/notation-of-er-diagram-ppt.php

M.A.Dyade

You might also like