Database 2

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 70

PROGRAM TITLE: BTEC Computing

UNIT TITLE: Database Design & Development


ASSIGNMENT NUMBER: Assignment 1
ASSIGNMENTNAME:Phone Management System
SUBMISSION DATE: 10/11/2022
DATE RECEIVED: 20/11/2022
TUTORIAL LECTURER: Luong Thi Thao Hieu
WORD COUNT: 5650

STUDENT NAME: Nguyễn Văn Thịnh


STUDENT ID: BKC13107
MOBILE NUMBER: 0325925546
Summative Feedback:
Internal verification:
Contents
I. Introduction .................................................................................................................................... 6
II.Theory ............................................................................................................................................... 7
1. Database ......................................................................................................................................... 7
1.1 What is database? ........................................................................................................................... 7
1.2 Purpose of the database .................................................................................................................. 8
1.3 The role and importance of databases ............................................................................................ 8
1.4 Some kind of database.................................................................................................................... 9
2. Relational database......................................................................................................................... 9
2.1 What is a relational database? ........................................................................................................ 9
2.2 Components of a Relational Database.......................................................................................... 10
3. Entity Relationship Diagram (ERD) ............................................................................................ 12
3.1 What is an entity relationship diagram? ....................................................................................... 12
3.2. What is the purpose of an entity relationship diagram? .............................................................. 13
3.2 What are the components of an entity-relationship diagram? ...................................................... 13
Some tools for drawing ERD ....................................................................................................... 17
4. Relational schema ........................................................................................................................ 17
4.1 What is a relational schema? ........................................................................................................ 17
4.2 What is the purpose of relational schema? ................................................................................... 18
4.3 How to convert ERD to relational schema ................................................................................... 18
5. Relational database management system ..................................................................................... 18
5.1 What is a relational database management system? ..................................................................... 18
5.2 The role of the database management system .............................................................................. 19
5.3 Some database management systems ........................................................................................... 19
6. Standardized data ......................................................................................................................... 20
6.1 Database Normalization ............................................................................................................... 20
6.2 Types of database normalization .................................................................................................. 20
7. Query language ............................................................................................................................ 24
7.1 What is query language? .............................................................................................................. 24
7.2 Commands in query language ...................................................................................................... 25
8. System testing .............................................................................................................................. 26
8.1 What is testing? ............................................................................................................................ 26
8.2 The purpose of testing .................................................................................................................. 26
II. Practice ......................................................................................................................................... 27
1. Analysis the real problem............................................................................................................. 27
2. Entities.......................................................................................................................................... 27
3. Entity Attributes ........................................................................................................................... 27
4. Relationships of entities ............................................................................................................... 27
- Product give information about produc. ....................................................................................... 27
5. ERD .............................................................................................................................................. 28
1. Relational schema ......................................................................................................................... 28
2. Constraints of DB ......................................................................................................................... 29
3. Detail settings ............................................................................................................................... 29
4. DB table ....................................................................................................................................... 30
5. Query statements in the created database..................................................................................... 31
6. Normalize created database.......................................................................................................... 35
7. System security, database maintenance ....................................................................................... 37
III. Apply test to selected DB............................................................................................................. 40
1. Test log ......................................................................................................................................... 40
2. Test case ....................................................................................................................................... 41
IV. User technical documentation ...................................................................................................... 42
1. Instructions to install used RDBMS ............................................................................................. 42
2. Instruction .................................................................................................................................... 45
son how to import sql files into SQL Server ...................................................................................... 45
Option1: Usedetach database................................................................................................... 45
Method 2: Export .sql file ..................................................................................................... 47
3.How to use File scripts.sql............................................................................................................... 51
3. Instructions for using RDBMS on ................................................................................................ 54
Step 1: Connect ............................................................................................................................ 58
Step 2: Execute a query ............................................................................................................... 59
In this sample, connect to Azure SQL Database, execute a SELECT statement, and return
selected rows............................................................................................................................ 59
I. Introduction

In a small operation, the network admins or developers double up as database admins


(DBAs). In larger businesses, there might be dozens of DBAs specializing in the
many different facets from design and architecture, to maintenance, development,
etc. No matter what part of IT you work in, you have to store data at one point or
another, and it doesn't hurt for just about everybody to have some knowledge of
databases and how they work.

We're going to explain the basics of what a database actually is, look at the history,
understand relational databases, get into some fundamental concepts from columns
and rows on up, touch on other types of databases

II.Theory

1. Database

1.1 What is database?

- Database is a word commonly used in the fields of information technology, data,


programming and software. Database is a database, is a collection of data that is
organized and displayed and is often stored. accessed from the computer system or exists
as a file in the database management system. Database can also be stored on memory
devices such as memory cards, hard disks, CDs, etc.
1.2 Purpose of the database

− The purpose of a database is to collect, store and manage data. Databases exist
as files in computer operating systems or database management systems. They
are stored on memory devices such as hard drives, USB drives, CDs, etc.

1.3 The role and importance of databases

- Archive information with system: Computational systematic structure arrangement -


this is what makes the biggest difference between conventional data and database
databases. Data will be stored in a structured, highest-consistent format. With this
feature, the database makes it convenient for users to create, store, search and use data
accurately and quickly.

- Secure all data: Total security and complete data is the key point of surrender in data
storage impact. And the database deserves a “10” on the entire data set. If you want to
save the text file to data, you should use the .xml file and the .csv file is best. When you
save to two file types, you can easily and securely convert to a database. This is normal
is used in the external database backup to readable.

- Ensure simultaneous access of multiple users' capabilities on data: Lots of people can
use the database at the same time without going through complicated points by accessing
from different ways. Therefore, you will have many advantages in using, managing,
accessing data, etc.

- Flexibility to change according to user needs: You have the flexibility to change the
complexity and size of a database. There are databases that consist of only a few hundred
records (a list of students in a class) and there are databases that have a very large
capacity (such as the inventory management database of a supermarket). At the same
time, the database storage format is also quite diverse. Databases can be stored in various
formats such as hard drives, USB sticks or CDs.

- Easier management: A database is designed, configured, and stored to make it easy to


set up, update and exploit information. The data will be updated regularly and not
completely repetitive. Using the database helps to create professional products, store
them systematically, and easily manage work. With that priority, databases are
increasingly popular in the field of application setup in particular and technology in
general.

1.4 Some kind of database

Relational Database Management System – RDBMS (Oracle, MySQL, MS


Server, PostgreSQL)
Document store (MongoDB, Couchbase)
Key-value databases (Redis, Memcached)
Wide-column model (Cassandra, HBase)
Search engine database (Elasticsearch)

2. Relational database
2.1 What is a relational database?

- A relational database is a type of database that stores and provides access to data
points that are related to one another. Relational databases are based on the relational
model, an intuitive, straightforward way of representing data in tables. In a relational
database, each row in the table is a record with a unique ID called the key. The columns
of the table hold attributes of the data, and each record usually has a value for each
attribute, making it easy to establish the relationships among data points.

2.2 Components of a Relational Database

- Table: A data table is a key component in a relational database. The table contains
the data.

Field: The fields represent attributes of the data table such as name, address, etc.

Row: Is a data stream consisting of related data, also known as a record

Cell: Intersection between rows and columns and where data is stored

Primary Key: Is a field or fields combined used to define a record. Primary key has
02 attributes that cannot be duplicated and cannot be null. For example, the value 1
of that Customer ID field will infer all the data of the first row. In other words, the
values of the first row are the values of the attributes of the table with customer ID =
1.

- Relationship:

One-to-one relationship: In this relation, each table has only one and only one
corresponding record. For example husband-wife relationship, relationship Basic
information – Details…

One-to-n relationship: As the most common relation in the database, in this


system 1 table in one table has many corresponding records in the other table. In the
above example, a table in the Customer table has many records in the Invoice table.

n-to-n relationship: in this relation one table in one table corresponds to many
records in the other and vice versa.

- ERD: Entity-relationship diagrams help you understand more quickly about structured
database systems, making it easier for you to work with them.
Database Management System – DBMS : DBMS is the software used to manage
and operate the Database. Popular DBMSs like MySQL, SQL Server, Oracle
Database, DB2...

3. Entity Relationship Diagram (ERD)


3.1 What is an entity relationship diagram?

- An Entity Relationship (ER) Diagram is a type of flowchart that illustrates how


“entities” such as people, objects or concepts relate to each other within a system. ER
Diagrams are most often used to design or debug relational databases in the fields of
software engineering, business information systems, education and research. Also
known as ERDs or ER Models, they use a defined set of symbols such as rectangles,
diamonds, ovals and connecting lines to depict the interconnectedness of entities,
relationships and their attributes. They mirror grammatical structure, with entities as
nouns and relationships as verbs.
3.2. What is the purpose of an entity relationship diagram?

- Helps define terms related to entity-relationship modeling.


- Give a demo to preview how all the tables in the DBMS will be connected,
what fields or attributes will be present on each table.

- Describe entities, attributes, and relationships.


- Entity-relationship diagrams can be converted to relational tables, thus
allowing for rapid database construction.

- Entity-relationship diagrams are used by database designers as a blueprint for


implementing data in applications and software.

- ERD allows to convey the logical structure of the database to the user.

3.2 What are the components of an entity-relationship diagram?

- Entities: A thing in the real world, whether it exists or not, that may or may not be
recognizable. It can be anything in an organization that can be represented in a database.
It can be an object, a business piece of information, or a real-world event. An entity can
be a place, person, object, event or concept that is stored data in a database. Entities
characteristics must have an attribute and have a key attribute, called a key, to easily
identify the entity as unique. Every entity is made up of some attribute that represents
that entity.

 Weak entity and strong entity

Strong entity Weak entity


There is always a primary key Not enough attributes to generate primary
key
Represented by a rectangle Represented by a rectangular symbol with
2
sides
Contains the primary key represented by Contains a partial key represented by an
the underlined dashed line.
underscore.
Members of a set of strong entities are A member of a weak entity set is called a
called top-level entity sets low-level entity set
Primary key helps to identify members of a Must include combination of primary key
set of strong entities and
partial key of strong entity set
In an entity-relationship diagram, the The relationship between a set of strong
relationship between two strong entity sets and weak entities is represented by a 2-
is sided
represented by a rhombus rhombus
The connection line between a set of strong The connecting line between a set of weak
entities and a relationship is a simple line entities is a double line

- Relationship: A relationship is an association between two or more entities. Entities


that participate in one or more relationships. Relationships are often defined to include
things or events with verbs that affect each other.

- Properties: A trait containing a value for an entity type or a relation type. Example:
A lecture can have attributes like time, date, duration, location.
-> Attributes are represented by an ellipse
Attribute Types Describe
Single attribute Attributes cannot be subdivided anymore. A
student's contact number, for example,
is called an atomic value.
Synthetic properties Aggregate properties can be subdivided. For
example, a student's full name can be divided
into last name, first name, and last
name.
Derived Attribute This attribute type is not included in the
physical database. However, their values are
derived from other attributes present in the
database. For example, a student's age can be
calculated from the date of
birth.
Multivalued attribute Multivalued attributes can have multiple values.
For example, a student may have more than one
cell phone number or email
address.
- Symbols of components in an entity-relationship diagram

 Rectangle: Represents the type of the entity


 Ellipses: Representation for attributes

 Rhombus: Representation for relationship types


 Lines: It associates properties with entity types and entity types with
other relationship types

 Primary Key: Are the underlined attributes

 Ellipses with 2 sides: Representation for multi-valued attributes


Some tools for drawing ERD
• Moqups
• Diagram.io
• SqIDMB
• Dbdesginer.net
• Dataedo
• Vertabelo
• Diagram.io

4. Relational schema
4.1 What is a relational schema?

- A relational schema is a set of relational tables and associated items that are related to
one another. All of the base tables, views, indexes, domains, user roles, stored modules,
and other items that a user creates to fulfill the data needs of a particular enterprise or
set of applications belong to one schema.
4.2 What is the purpose of relational schema?

- The goal of the E-R model in database design is to analyze the data, identify the basic
units of information needed by the organization, and describe their structure and
relationships.
4.3 How to convert ERD to relational schema

- Converting files can: Each entity is converted to a relation with the same name and
attribute list. For regular entity type: The key of the relation is the key of the entity type.
The attribute of the relation is also the property of the entity type. The relation does not
contain multivalued attributes, but only the member attributes of the composite
attributes.

- Switch 3 star relationship: Convert to a new relationship, with a primary key consisting
of 3 key attributes of the 3 entities participating in the association. The association
attribute (if any) will become the attribute of the new relationship.

- Transformation relationship 1 - 1: One side's key attribute will be the other party's
foreign key or vice versa.
- Transform 1 – n relationship: Attribute 1 side key as a many-party foreign key.
- Convert n - n relationship: Convert to a new relationship with a primary key consisting
of 2 key attributes of 2 or more relations, the association attribute (if any) becomes an
attribute of the new relation.
- Convert multivalued relationship: Convert to a new relationship with a primary key
consisting of a multivalued attribute and an entity key attribute. After converting to a
new relationship, the multivalued attribute will automatically disappear from the old
entity.
5. Relational database management system
5.1 What is a relational database management system?

- A relational database management system (RDBMS) is a collection of programs and


capabilities that enable IT teams and others to create, update, administer and otherwise
interact with a relational database. RDBMSes store data in the form of tables, with most
commercial relational database management systems using Structured Query Language
(SQL) to access the database.
5.2 The role of the database management system

Provide a database creation environment: The database management system


plays the role of providing users with a data definition language to describe
and declare data types and data structures.
Provides a way to update and exploit data: The DBMS provides users with a
data manipulation language to express database requests, updates, and
operations. Data manipulation includes: Update (import, edit, delete data),
Mining (search, dump data).

Provide tools to control and control access to the database to ensure the
fulfillment of some basic requirements of the database system. Including: (1)
Ensuring security, detecting and preventing illegal access. (2) Maintain data
consistency. (3) Organize and control access. (4) Restore the database in the
event of a hardware or software failure. (5) Manage data descriptions.
5.3 Some database management systems

MySQL: MySQL is the world's most open source self-administered database


and is very popular with developers during application development. Since
MySQL is a high speed, stable and easy to use database, it is portable, works
on many operating systems providing a large system of very powerful
functions. With high speed and security, MySQL is very suitable for
applications with databases accessing on the internet. It has many versions for
different operating systems: Win32 version for Windows, Linux, Mac OS X,
Unix, FreeBSD, NetBSD, Novell NetWare, SGI Irix, Solaris, SunOS, ...
SQL Server: Microsoft SQL Server is a database management system that
provides a way to organize data by storing them in tables. Relational data is
stored in tables, and those relationships are defined between the tables. Users
access data on the Server through the application. Database administrators
access the Server directly to perform configuration, administration and
database maintenance operations. In addition, SQL Server is a scalable
database, which means that they can store large amounts of data and support
the feature that allows multiple users to access data concurrently. The versions
of the popular SQL Server currently on the market are SQL Server 7.0, SQL
Server 2000, SQL Server 2005, SQL Server 2008, ...
DB2: DB2 is one of IBM's line of relational database management software.
It was first released in 1982 and is currently available for a wide range of
operating system platforms, mainly used on Unix (commonly called AIX),
Linux, IBM i (formerly OS/400), z/OS and Windows Servers. DB2 uses the
SQL language to read and write information to data.

Oracle: No wonder Oracle is considered the most popular database


management system in the world. Oracle has been at the forefront for many
years since its inception in 1979. What can be said about Oracle is "a complex
but powerful system". Oracle is moving towards the cloud data model in
release 12c, allowing companies to consolidate and manage databases as
cloud services.

6. Standardized data
6.1 Database Normalization

- Database Normalization is a database design technique that reduces data redundancy


and eliminates undesirable characteristics like Insertion, Update and Deletion
Anomalies.
Normalization rules divides larger tables into smaller tables and links them using
relationships. The purpose of Normalisation in SQL is to eliminate redundant
(repetitive) data and ensure data is stored logically.

6.2 Types of database normalization

- There are basic forms of normalization:


First Normal Form (1NF): A table (relation) is said to be in 1NF normal form if
and only if all the domains of the columns present in the table (relation) contain only
atomic (prime) values.
The first normal form requires that a table satisfies the following conditions:
1. Rows are not ordered
2. Columns are not ordered
3. There is duplicated data
4. Row-and-column intersections always have a unique value
5. All columns are “regular” with no hidden values

After normalization, the normalized tables Dept and Employee looks like below:
Second Normal Form (2NF): A relation is in 2NF normal form if the relation as 1NF,
Non-key attributes must be fully functionally dependent on the primary key.
In this example, the Title column is functionally dependent on Name and Date columns.
These two keys form a composite key. In this case, it only depends on Name and
partially dependent on the Date column. Let’s remove the course details and form a
separate table. Now, the course details are based on the entire key. We are not going to
use a composite key.

Third Normal Form (3NF): A relation is in 3NF normal form if it is 2NF,Non-key


attributes must depend directly on the primary key.
Consider the following example, in the table employee; empID determines the
department ID of an employee, department ID determines the department name.
Therefore, the department name column indirectly dependent on the empID column. So,
it satisfies the transitive dependency. So this cannot be in third normal form.
In order to bring the table to 3 NF, we split the employee table into two.

7. Query language
7.1 What is query language?

- It is a common name for computer languages used to create queries in databases and
information systems.
7.2 Commands in query language

a. Create

b. Select

c. Where

d. Insert into
e. Update

f. Delete

g. Joins

8. System testing
8.1 What is testing?

- It is an activity to find and detect software errors, to ensure that the software is accurate,
correct and complete according to customer requirements and product requirements.
8.2 The purpose of testing

- Software testing to assess whether the software meets the expectations or has any
flaws?
- Is the software working as expected?
- Does the software meet the customer's requirements? Does it do what the user expects?
- Do users like it?
- Is it compatible with our other systems?

II. Practice
1. Analysis the real problem

- Building a system database for a phone retail store named “Thinhstore”. The system
includes a store that sells smartphone products to consumers. In addition, the store will
have staff with the task of managing orders and smartphone products. The products will
be divided according to many types of product categories of the store. For online orders,
it will be delivered to the shipping department for direct delivery to the customer.
2. Entities

- Customer
- Invoice
- InvoiceDetail
- Product
- Sale
- Shipper
- Supplies
3. Entity Attributes

- Customer (idCus,contactname,addres,phone)
- Invoice (idOrder , orderdate , shipdate , shipname , shipaddress)
- InvoiceDetail(idInvoice, price , quantity , discount )
- Product (IMEI , name , releaseDate , capicity , size)
- Sale(idSale , name , phone , addres , mgid)
- Shipper ( idShip , phone , company)
- Supplies ( idSup , companyname , country , phone )
4. Relationships of entities
- Product give information about produc.
- supplies provide more product
- customer buy more product
- sale sale product
- shipper ship product
- all information about them are writen down in invoice and invoice detail

5. ERD

1. Relational schema
2. Constraints of DB

3. Detail settings

- Customer

- Supplies

- Shipper
- Sale

- Product

- Invoice

- InvoiceDetail

4. DB table
5. Query statements in the created database

* Insert

- Insert into table Customer

- Insert into table Supplies

- Insert into table Shipper

- Insert into table Sale

- Insert into table Product


- Insert into table Invoice

- Insert into table InvoiceDetail

* Select

- Select table Customer

- Select table Supplies

- Select table Invoice


- Select table InvoiceDetail

- Select table product

- Select table sale

- Select table Shipper


* Update

* Delete

* query with condition:


• export ra near true name

--take customer’name have character “c” in .

• multi-condition query

--check out the customer’name buy what product:

6. Normalize created database


* Inner join
-- export information about customer and their Invoice

*group by:
-- take out the customer ‘name and how many Invoice thay have

*Union
Take out the list of customer and shipper

select contactname from dbo.Customer


union
select shipname from dbo.Invoice
7. System security, database maintenance
The protection of databases is essential to various industries and sectors , such as
finance , banking eCommerce, and IT. Most of your transactions are based on your
database’s security because it holds vital details, such as passwords, usernames,
customer credit card details, etc
Different Levels of Protecting a Database

Database protection has different levels to it. Here are some of the standards for
protecting a database:

• Data-Level Security: This is the process of securing data from getting tampered with
or stolen within the server.
• User-Level Security: When they attack a server, they do so from the user level. This
is why organizations look towards real-time protection software for monitoring
transactions and restricting users from visiting unauthorized websites or downloading
from untrusted sources.
• System-Level Security: This is to protect network servers, hardware, and other
outbound/inbound communications from working as the channel for distributing
malicious software.

Most Common Types of Database Attacks

There are different types of database attacks, but the ones that most threaten the
security of the database are:
• DoS attacks
• Privilege escalation
• Buffer overflow vulnerability
• SQL injection threats
• Weak authentication

Data Security Best Practices: There are some best practices recommended by experts
to ensure data security. Some methods that are most trusted and widely used to ensure
data security are:

Physical Security: This is one of the first methods to secure physical servers. It
mainly requires digital locks and the use of CCTV cameras to continuously monitor
the data and secure the premises 24/7, preventing unauthorized entry.

Establish Policies for Security and Compliance: You have to define your standards
and security policies clearly. This will ensure that your enterprise won’t have to
struggle with assessing compliance or measuring the progress against its benchmarks.
Most times, organizations develop strong security policies for their data because it
moves through the network. However, they fail to map these policies back to their
database by themselves.

When weaknesses in security are remediated, this is mostly a reaction to the incident
instead of being a proactive response as a result of policies. Businesses always have to
review their policies after patching the vulnerabilities or installing a newer version of
the software. This is so that they can account for settings and configurations that they
have updated. When establishing standards and policies, the data security team has to
ensure that they address how they update their policy regularly, who is in charge of the
updates, what is meant to trigger a change of policy, and the process of approving a
policy change.

Use a Strong Database Software: You can use an open-source database software or a
version paid for and supported by a vendor. This software will run on only active
devices, but on inactive devices, it will be unplugged, and the default accounts that are
not in use will be periodically removed. Security patches should be applied timely.

You also have to look closely at the vendor of your software to determine how they are
keeping the code very secure.

Database Auditing and Change Management: A security measure is essential for


keeping track of change management to log into database activities. All the login data
is maintained at least yearly for security audits, and all the accounts that face the
maximum attempts of failed logins will trigger an automatic notification to the
database administrator, so the necessary steps can be taken.

Implementing Application Code: The DBAs will ensure that the source codes and
configuration files are accessible through authorized accounts of the operating system.
Application codes should be reviewed regularly to ensure that they are not vulnerable
to the injection of SQL.

Establishing Server Firewalls: You can set all connections to your database to ensure
it denies all incoming traffic using a firewall. This means that it will block access for
direct clients and give access to only authorized applications. The database
administrators (DBAs) and system administrators (SAs) strictly maintain and monitor
firewall rules. They are also responsible for performing ISP scans and network scans
for strengthening the server machines.

Role of DBAs and SAs: The role of SAs and DBAs are vital as they play a significant
role as strict administrators. Only selected people have proper authorization, and they
all sign an NDA after a background check.

The DBA staff are allowed to use personal accounts to access the server and not share
accounts. These people have to build and maintain a very strong password to meet all
the necessary safety and security guidelines.
The Three Concepts of Database Security

Three main concepts are essential for database security. These are:

1. Confidentiality: It is vital to maintain confidentiality. You can do this through


enforced encryption of data that you’ve transferred and those stored within the
database in case of a breach.

2. Integrity: The control system for the user system is to make sure that only
authorized personnel are allowed to access the data, and the log is maintained so
everybody can access it. This will ensure that there is no breach of data caused by
errors.

3. Availability: The data stored within the system is available to both the
administrators and users, reducing downtime. The servers are updated periodically to
ensure maximum security while also boosting the job through continuous service.

Conclusion

When the administrator of the database is aware of the most common threats, they
implement these different methodologies for data protection and make sure that they
store the data in servers that are extremely protected. These best practices will ensure
that the data recovery and backup are able to safeguard the data against ransomware.

III. Apply test to selected DB


1. Test log

As in the table of customers, customer age is declared as an integer, so the program


only allows declaring integers if we enter letters, the program will display an error
on the terminal.

-> Fix: Enter the correct format for age “INT”

2. Test case

-> Fix: Convert name_customers data type to varchar(255)

3. Trigger:
Trigger will be called when there is a change to the table :
Inserted : contains the information that has been inserted
Deleted : contains the information that has been deleted

----Prevent deletion of a position with idcus =100


IV. User technical documentation
1. Instructions to install used RDBMS

- Start type Microsoft SQL management studio 18 and open it

- Click connect to connect to a server


- Click “File” then “Open” the file you have created
- Your code screen will look like this
2. Instruction
son how to import sql files into SQL Server
I have 1 Database name: Thinhstore in this with Table customer swith pre-
inserteddata,now I want to send this Database to anotherperson to useor
Iwantto copytoanother computerusingSQL Server. And the following will be how to
import .sql file into the sql server that I use.

Option1: Usedetach database


Step 1: Right-click Database > Tasks > Detach...
How to import .sql file into sql using Detach Database
Step 2: Copy2 Database files
*Usually these 2 files in theDatafolder, you access the following path:

Copy 2 Database files


*You just need tosendthese 2 files topeople aroundyou torecover data on a completely
different computer
Step 3: Restore on another machine
After receiving these 2 files, you paste these 2 files into the link below.
Path: C:\Program Files\Microsoft SQL Server\MSSQL11.
SQLEXPRESS\MSSQL\DATA
Done pasting youAttach... re-Database
Execute:Right-click Database > Attach.. ≫ Add >select ThinhStore.mdf > OK >
OK
Restore on another machine Database Thinhstore has just successfully transferred
Then you will see that the databasehas justbeen successfully added! Ifyoudon't have
one, refresh to see that the databaseis justin SQL Server!

Method 2: Export .sql file

This way we will export theconfiguration file.sql from one machine and run this .sqlfile
onanothermachine to get the "Database" to be restored.
Step 1: Right-clickonDatabaseselectTasks>Generate Scripts...
Right-click on Database -> Tasks -> Generate Scripts

Step 2: ClickNexttocontinue
Click Next...

Step 3: Select1 numberoftablesorclickgetall (Inthe imageI willscanall) selectSelect


specific database objects >checkTables
Select Table to export
Step 4: To export .sql file with data, you need toconfigureasfollows: Advanced>
At:Types of datatoscriptselect "Schema and data" >OK>Next

Export sql file with data


Step 5: ClickNexttocontinue
Click Next
Step 6: Check the export statusof the file andclickFinishto completethescript export.sql
Finish

By doingso we can successfully export the script file.sql located in the


path:C:\Users\vip\Documents\script.sqland we will proceed to run this script file.sql.
3.How to use File scripts.sql
Step 1: Open SQL Serverselect File>Open>File...
Step 2: Select the script file.sql toopenin SQL Server

Select the script file.sql to open in SQL Server


Step 3: We need to create 1 Database similar to the name of the old Database to
contain the data we are about to enter.
For example: In this case we must create a Database namedThinhstore

Create the same database as the old one


Step 4: Selectallcommands andclickExecute. The resultwhen successful will show the
message:Command(s) completed successfully. Open The Thinhstore database will
seeallthe tables and data we need.
3. Instructions for using RDBMS on

- First click Excute

- And here is the result of table


- About diagram, double click the database to open diagram

- Choose all entity to add to diagram

- Finally we have diagram in


V. T-SQL

1.declare and using variable:

• Take out the average price of product:

2 . if- else

*compare the value of price of column idOrder = 7725 in table Invoicedetail

If the variable @priceAverage is greater then update the price = @priceAverage


Else print “the price is less than price average”

3.create function in SQL:

-- create 1 function to save operation time and malnipulate

Create function to take out ‘ContracName’ in table Customer with parameter @id

Call function :

Output:

1. Cursor

---------cursor is using to point out the value at position that you want to look at

Create cursor:

◼ This cursor is using to point at table that have 2 column are ‘’ContractName’’
and ‘’ Phone’’ in table dbo.Customer
Out put :

VII. JDBC:
Step 1: Connect
Use the connection class to connect to SQL Database
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class SQLDatabaseConnection {


// Connect to your database.
// Replace server name, username, and password with your credentials
public static void main(String[] args) {
String connectionUrl =
"jdbc:sqlserver://yourserver.database.windows.net:1433;"
+ "database=AdventureWorks;"
+ "user=yourusername@yourserver;"
+ "password=yourpassword;"
+ "encrypt=true;"
+ "trustServerCertificate=false;"
+ "loginTimeout=30;";

try (Connection connection =


DriverManager.getConnection(connectionUrl);) {
// Code here.
}
// Handle any errors that may have occurred.
catch (SQLException e) {
e.printStackTrace();
}
}
}
Step 2: Execute a query
In this sample, connect to Azure SQL Database, execute a SELECT statement, and
return selected rows.
import java.sql.Connection;
import java.sql.DriverManager;
ResultSet resultSet = null;

try (Connection connection = DriverManager.getConnection(connectionUrl);


PreparedStatement prepsInsertProduct =
connection.prepareStatement(insertSql,
Statement.RETURN_GENERATED_KEYS);) {

prepsInsertProduct.execute();
// Retrieve the generated key from the insert.
resultSet = prepsInsertProduct.getGeneratedKeys();

// Print the ID of the inserted row.


while (resultSet.next()) {
System.out.println("Generated: " + resultSet.getString(1));
}
}
// Handle any errors that may have occurred.
catch (Exception e) {
e.printStackTrace();
}
}
}

Interact with sql server with event-driven programming:


Step1 :
We create an Jframe form:
Step 2:
We add swing containers and controls :

Step 3:
Next to we optimise 6 option : insert, reaload , reset , delete, search , close
1: RELOAD :
It is used to fill up data in table :
Program in class connection:
Program in jframe form:

Result:
Delete function:
Insert function:
Search function :
Close function :

You might also like