You are on page 1of 36
DBMS Architecture * Describes the structure and how the users are connected to a specific database system * It also affects the performance of the database as it helps to design, develop, implement, and maintain the Database Management System. *The database management system design depends on the DBMS architecture for its representation. *It describes the structure and the way in which the users are connected to a specific database system. Types of DBMS Architecture DBMS Architecture t | Single Tier Two Tier ‘Three Tier Architecture Architecture Architecture | ¥ Y All the components (client, Follows client-server Itconsists of Application server, and database ) of architecture where the Layer in addition to Client DBMS reside on a single server provides DBMS and Server to provide load machine. functionality that the client. | | balancing and enhance DBMS accesses using APIs, security, Single Tier Architecture * Straightforward DBMS architecture * All the DBMS components reside on a single server or platform * i.e., the database is directly accessible by the end-user. «In this structure, any modifications done by the client are reflected directly in the database, and all the processing is done on a single server. *no network connection is required to perform actions on the database *This database management system is also known as the local database system. iti direct | od Database Example: One Tier DBMS Architecture Yin order to learn the Structure Query Language (SQL), we set up our SQL server and the database on our local system. ¥This SQL server enables us to directly interact with the relational database and execute certain operations without requiring any network connection. This whole setup to learn SQL queries is an example of Single-Tier DBMS architecture Example of Single Tier DBMS Architecture Local System User Direct Interaction Highlights vSimplest DBMS architecture. VAIl the components of DBMS, i.e., the server, database, and client, reside on a single system. vThe user can directly access the database. v Used when data isn't changing frequently. vSuitable for programmers, database designers, and single-user access. Two Tier Architecture * It is similar to the fundamental concept of client-server architecture. * In a two-tier structure, the server provides the database functionality and it allows the clients to perform operations on the database through a direct internet connection via APIs (Application Programming Interface) -—Aisall__ * For example: ODBC, JDBC API call APl call id Advantages v Multiple users can use it at the same time. Hence, it can be used in an organization. v It has high processing ability as the database functionality is handled by the server alone. v Faster access to the database due to the direct connection and improved performance. v Because of the two independent layers, it's easier to maintain. Example: Two Tier DBMS Architecture Sai) APL ; eT Server Accountant SQL Cs} Three Tier Architecture * It is the most widely used DBMS architecture * In which another layer known as Intermediate or Application layer is added between the server (Database Layer) and the client (Presentation Layer) systems to reduce the query processing load of the server. * Since there is no direct connection between the client and the Server, all the user requests are handled by the Application Layer. *i.e., the requests sent by the users are checked and verified by the Intermediate Layer before transferring them to the server. * This reduces the query processing load from the server. Continue.. * and enhances the security of the overall DBMS design as the client can't communicate directly with the database server. *The application layer is responsible for load balancing, query request correctness, and security in Three-Tier DBMS Architecture. Connection > plication Connection _[italenaed Layer Connection Advantages of Three Tier DBMS Architecture * Scalability - Since the database server isn't aware of any users beyond the application layer and the application layer implements load balancing, there can be as many clients as you want. * Data Integrity - Data corruption and bad requests can be avoided because of the checks performed in the application layer on each client request. * Security - The removal of the direct connection between the client and server systems via abstraction reduces unauthorized access to the database. Highlights v Most widely used DBMS architecture, ¥ Follows Client-Application-Server architecture, v Enhanced security, data integrity, and scalability, ~ Has complexity and maintenance issues because of the extra layer. Continue.. oRelation schema vA relation schema describes the relation name (table name), attributes, and their names. oRelation key v Each row has one or more attributes, known as relation key, which can identify the row in the relation (table) uniquely. oAttribute domain v Every attribute has some pre-defined value scope, known as attribute domain. Relational Model Keys * Keys play an important role in the relational database. * It is used to uniquely identify any record or row of data from the table. * It is also used to establish and identify relationships between tables. oa Pr) freee 1D hoa) Ect) feo ome on * For example, ID is used as a key in the Student table because it is unique for each student. In the PERSON table, passport_number, license_number, SSN are keys since they are unique for each person. Types of keys Keys Condidate super key Foreign |) Alternate Composite Artificial Key Key Key Key Key Primary key * It is the first key used to identify one and only one instance of an entity uniquely. * The key which is most suitable from those lists becomes a primary key. * For each entity, the primary key selection is based on requirements and developers. EMPLOYEE Crm Primary Key eam eed Candidate key + A candidate key is an attribute or set of attributes that can uniquely identify a tuple. * Except for the primary key, the remaining attributes are considered a candidate key. * The candidate keys are as strong as the primary key. EMPLOYEE eNom CLL) mes) | Condidate Key Super Key * Super key is an attribute set that can uniquely identify a tuple. * Itis a superset of a candidate key. EMPLOYEE Super Key Employee_Name * In the above EMPLOYEE table, for(EMPLOEE_ID, EMPLOYEE_NAME), the name of two employees can be the same, but their EMPLYEE_ID can't be the same. * Hence, this combination can also be a key. Foreign key * Foreign keys are the column of the table, * used to point to the primary key of another table. Pion Eien em cacy Crna) For Example: * Every employee works in a specific department in a company, and employee and department are two different entities. So we can't store the department's information in the employee table. That's why we link these two tables through the primary key of one table. Alternate key * There may be one or more attributes or a combination of attributes that uniquely identify each tuple in a relation. * These attributes or combinations of the attributes are called the candidate keys. * One key is chosen as the primary key from these candidate keys, and the remaining candidate key, if it exists, is termed the alternate key. *In other words, the total number of the alternate keys is the total number of candidate keys minus the primary key. * The alternate key may or may not exist. If there is only one candidate key in a relation, it does not have an alternate key. Continue.. ene TaD) — Primary Key } — conte ey PAN_No — Alternate Key * For example, * Employee relation has two attributes, Employee_ld and PAN_No, that act as candidate keys. * In this relation, Employee_ld is chosen as the primary key, so the other candidate key, PAN_No, acts as the Alternate key. Composite key @u + Whenever a primary key consists of more than one attribute, it is known as a composite key. * This key is also known as Concatenated Key. aT ona TE te Composite Key rym + For example, in employee relations, we assume that an employee may be assigned multiple roles, and an ‘employee may work on multiple projects simultaneously. So the primary key will be composed of all three attributes, namely Emp_ID, Emp_role, and Proj_ID in combination. So these attributes act as a composite key since the primary key comprises more than one attribute, Alter & Drop * The alter command, which changes to the structure of a table without deleting and recreating it. For Example: ALTER TABLE personal_info ADD salary money null; * Drop, removes entire database objects from our DBMS. + For example, to permanently remove the personal_info table that we created, use the following command: DROP TABLE personal_info; DROP DATABASE employees; Data Manipulation Language Commands * The Data Manipulation Language is used to retrieve, insert and modify database information. * These DML commands offer the typical framework for interacting wihtin the database on a routine basis. Insert * The insert command adds records to an existing table. Code: INSERT INTO personal_info values(‘bart’, 'simpson‘,12345 ,$45000); Select * The select command is the most commonly used command in SQL. * It retrieves specific information from an operational database. Code: SELECT * FROM personal_info; // Alternatively SELECT last_name FROM personal_info; // Where Cause SELECT * FROM personal_info WHERE salary > $50000; Update * The update command modifies the information contained within a table, either in bulk or individually. * For Example: company gives all employees a 3 percent cost-of-living increase in their salary annually. * Query: UPDATE personal_info SET salary = salary * 1.03; //The WHERE clause singles UPDATE personal_info SET salary = salary + 5000 WHERE employee_id = 12345; Delete * The DELETE command, with a where clause, remove a record from a table: * Query: DELETE FROM personal_info WHERE employee_id = 12345; * Note: DML supports aggregate fields, too. In a select statement, mathematical operators like sum and count summarize data within a query. * For example, the query: select count(*) from personal_info; * counts the number of records in the table. Python SQLite - Introduction * SQLite3 can be integrated with Python using sqlite3 module, which was written by Gerhard Haring. * It provides an SQL interface compliant with the DB-API 2.0 specification described by PEP 249. * You do not need to install this module separately because it is shipped by default along with Python version 2.5.x onwards. * To use sqlite3 module, you must first create a connection object that represents the database and then optionally you can create a cursor object, which will help you in executing all the SQL statements. Python sqlite3 module APIs ai) Sr. No. API & Description sqlite3,connect(database [,timeout ,other optional arguments]) This API opens a connection to the SQLite database file. You can use ":memory:" to open a database connection to a database that resides in RAM instead of on disk. If database is opened successfully, it returns a connection object. connection.cursor ([cursorClass]) This routine creates a cursor which will be used throughout your database programming with Python. This method accepts a single optional parameter cursorClass. If supplied, this must be a custom cursor class that extends sqlite3.Cursor. cursor.execute(sq} [, optional parameters]) This routine executes an SQL statement. The SQL. statement may be parameterized (ie placeholders instead of SQL literals). The sqlite3 module supports two kinds of placeholders: question marks and named placeholders (named style). For example - cursor.execute("insert into people values (?, ?)", (who, age)) connection,execute(sql [, optional parameters}) This routine is a shortcut of the above execute method provided by the cursor object and it creates an intermediate cursor object by calling the cursor method, then calls the cursor's execute method with the parameters given. Continue.. & Gai) cursor.executemany(sql, seq_of_parameters) 5 _ This routine executes an SQL command against all parameter sequences or mappings found in the sequence sq]. connection.executemany(sql[, parameters]) This routine is a shortcut that creates an intermediate cursor object by calling the 6 cursor method, then calls the cursors executemany method with the parameters given, cursorexecutescript(sql_script) This routine executes multiple SQL statements at once provided in the form of script. 7 Itissues a COMMIT statement first, then executes the SQL script it gets as a parameter. All the SQL statements should be separated by a semi colon (;). connection.executescript(sql_script) This routine is a shortcut that creates an intermediate cursor object by calling the cursor method, then calls the cursor's executescript method with the parameters given. connection.total_changes() 9 This routine returns the total number of database rows that have been modified, inserted, or deleted since the database connection was opened. Continue & Gai) 10 11 12 13 14 15 connection.commit() This method commits the current transaction. If you don't call this method, anything you did since the last call to commit() is not visible from other database connections. connection.rollback() This method rolls back any changes to the database since the last call to commit() connection.close() This method closes the database connection. Note that this does not automatically call commit(). If you just close your database connection without calling commit() first, your changes will be lost! cursor.fetchone() This method fetches the next row of a query result set, returning a single sequence, or None when no more data is available. cursor.fetchmany [size = cursor.arraysize]) This routine fetches the next set of rows of a query result, returning a list. An empty list is returned when no more rows are available, The method tries to fetch as many rows as indicated by the size parameter. cursorfetchall(Q) This routine fetches all (remaining) rows of a query result, returning a list. An empty list is returned when no rows are available. Create Table using Python import sqlite3 #Connecting to sqlite conn = sqlite3.connect('example.db') #Creating a cursor object using the cursor() method cursor = conn.cursor() #Doping EMPLOYEE table if already exists. cursor.execute("DROP TABLE IF EXISTS EMPLOYEE") #Creating table as per requirement sql =""CREATE TABLE EMPLOYEE( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT ye Continue... cursor.execute(sql) print("Table created successfully... # Commit your changes in the database conn.commit() #Closing the connection conn.close() Python SQLite - Insert Data import sqlite3 Connecting to sqlite conn = sqlite3.connect('example.db') #Creating a cursor object using the cursor() method cursor = conn.cursor() # Preparing SQL queries to INSERT a record into the database. cursor.execute(""INSERT INTO EMPLOYEE( FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES (‘Ramya’, ‘Rama Priya’, 27, 'F', 9000)"") # Commit your changes in the database conn.commit() print("Records inserted...... ") # Closing the connection conn.close() Retrieving data using python import sqlite3 #Connecting to sqlite conn = sqlite3.connect('example.db') #Creating a cursor object using the cursor() method cursor = conn.cursor() #Retrieving data cursor.execute(""'SELECT * from EMPLOYEE") #Fetching 1st row from the table result = cursor.fetchone(); print(result) #Fetching 1st row from the table result = cursorfetchall(); print(result) Continue.. #Commit your changes in the database conn.commit() #Closing the connection conn.close()

You might also like