Oracle Basic Knowledge

Source: Internet
Author: User

One, the Oracle installation process is slightly

II. SYS user and system user

(1) SYS user is superuser, has the highest privilege, has SYSDBA role, has CREATE DATABASE permission

The default password is Change_oninstall

(2) The system user is the management operator, the authority is also very large, has the sysoper role, but does not have the CREATE DATABASE permission, the default password is the manager

(3) General maintenance of the database, using the system user login is sufficient

Iii. Startup of Oracle

The so-called start-up is an instance of starting Oracle, ORACLESERVICEORCL, which must be started when using Java to connect to a database, otherwise it will not be able to use JDBC.

Iv. Oracle's Data Objects

In Oracle, tables, views, stored procedures, triggers are referred to as data Objects in Oracle

V. Oracle Management Tools

Sqlplus is Oracle's own tool software that is used primarily to execute SQL statements

One, the following is sqlplus Common command

(1) Conn[ect]

USAGE: Conn User name/password @ NETWORK SERVICE name [as Sysbda/sysoper]

Must take as sysbda/sysoper when the user is a privileged user

Example: Conn System/manager

(2) Disc[onnect]

Disconnect Connection

(3) Passw[ord]

Modify the password when you want to modify other user passwords with SYS or system login

(4) Show user

Show Current User

(5) Exit

Disconnect, and Exit Sqlplus

Second, the file Operation command

(1) Start, @

Description: Run SQL script

For example: Under D: a.sql This file, run the following command to execute the contents of A.sql

sql>@ D:a.sql or

Sql>start D:a.sql

(2) Edit

Edit the specified SQL script

Sql>edit D:a.sql

(3) Spool

This command allows you to export the contents of the Sqlplus screen to the file you have developed.

Sql>spool D:b.sql

Sql>select * from EMP;

Spl>spool off

Description: The spool command outputs the query result of the SELECT * from EMP to a file in the specified location and then spool off similar to IO on/off

Iii. Interactive Commands

(1) &

can override a variable that requires user input when executing

Sql>select * from emp where job= ' &job ';

Oracle prompts the user to enter a value

Iv. Displaying and setting environment variables

Can be used to control the output of various formats, if you want to permanently save the relevant settings, you can modify the Glogin.sql script

(1) linesize

Sets the width of the display line, which defaults to 80 of its own characters

Sql>show linesize

Sql>set Linesize 120

(2) pagesize

Set the number of rows displayed per page by default is 14, use the same linesize

The use of other environmental parameters is similar

One, Oracle User management

Create user , DBA authority required

Command:Create user "username" identified by "password"

Change Password

Command:password "user name" (in case the user is already connected)

Note: You need to have DBA authority or have alter user's system permissions when changing passwords to other users

Command:alter user "username" identified by "New password"

Delete User

Typically remove users as DBA

If the user you want to delete has created a table, add a parameter to the delete cascade

Command:drop user "username" [Cascade]

Ii. Rights and Roles

New users that have just been created do not have any permissions or even permissions to log on to the database. It is time to use conn "username"/"password" to prompt for no permissions.

This user is also authorized after a new user is created. Of course, to use a user with the ability to authorize, such as SYS, system

Permissions include system permissions and object permissions

System permissions: User-related permissions to the database

Object permissions: The user's permission to manipulate data objects for other users

Role

A role is defined by a collection of system permissions. Usually when a user is granted permission, if no role exists, then a single action is required, the presence of the role

is to make authorization very convenient. Typically a role consists of multiple system permissions. The commonly used roles are three connect (7 permissions), DBA, resource (in any table space).

Here is a simple mention, which will be studied later as a topic.

To assign permissions to a user by using the GRANT command:

Grant "Permission name" to "User name"

Assigning roles :

Grant "role name" to "User name"

Revoke permissions :

Revoke "permission name" from "User name"

Give an example to illustrate:

1. Create user

Create user Stu identified by Stu;

2. Enable Stu to be connected

Grant create session to Stu;

3. Allow Stu to build tables in any table space

Grant resource to Stu

3. Create a simple table

CREATE table users (name VARCHAR2, age number (2));

4. Insert several data

Insert into users values (' Houjinxin ', 22);

5. Log in to Scott to give Stu authorization so Stu can view the EMP table under Scott

Grant SELECT on the EMP to Stu;

6. Login to Stu to view the EMP table

SELECT * from Scott.emp;

If you want to update the data in Scott.emp at this time

Update scott.emp set ename= ' Ok2 ' where ename= ' OK ';

Will prompt ORA-01031: insufficient permissions. Because Scott only gives Stu the right to view it, and if he still wants to update it, he wants to authorize it under Scott.

7. Log in to the system to reclaim the resource role

Revoke resource from Stu;

8, login Scott under the recovery of SELECT permissions

Revoke select on the EMP from Stu;

This is Stu can no longer query the scott.emp data.

Transfer of permissions

When you want Stu users to be able to query Scott's EMP table, you also want Stu to continue to pass this permission to other users

If you want to pass object permissions , join with GRANT option

Grant SELECT on EMP-stu with GRANT option

If system permissions : Add with admin option

Grant connect to Stu with admin option

The ability to grant Stu to other users when the system authorizes Stu

Do an experiment to verify the

1, login to the system user, re-establish two users

Create user hou identified by Hou;

Create user Jin identified by Jin;

and assign the connect role to the Hou

Grant connect to Hou with admin option;

2. Login to Scott next Hou authorization

Grant SELECT on EMP-hou with GRANT option;

3, login to the Hou to start the licensing of Jin

Grant SELECT on Scott.emp to Jin;

Grant Connect to Jin;

4, Login to Jin under query scott.emp

SELECT * from Scott.emp;

To the current position is normal, the problem comes!

If the system withdraws the permissions assigned to Hou, then the permissions of Jin will also be recovered together and continue the experiment.

5. Log in to Scott to recover Hou permissions

Revoke select on the EMP from Hou;

Revoke connect from Hou;

6. Sign in to Jin to see the phenomenon

Found still able to log on to Jin on this note that the Connect role has not been retracted

ORA-00942 when querying scott.emp: Table or view does not exist

This indicates that the system permissions and object permissions are different. For system permissions, Hou is no longer withdrawn after it is assigned to Jin, and object permissions are retracted as Hou's permission is retracted.

Manage user passwords with profile

Profile is a collection of commands that restrict the password and resource constraints. When a database is established, Oracle automatically creates a profile named default. When the setup user does not have the profile option set, Oracle assigns default to the user.

(1) Account lockout

Specify the maximum number of times a password can be entered at logon, or specify the time, in days, that the user will be locked out. The general is to execute the command as a DBA. For example: Specifies that Stu can only attempt to log on for up to three times, with a lockout time of 2 days

Sql>create profile Lock_account Limit failed_login_attempts 3 password_lock_time 2;

Sql>alter user Stu Profile Lock_account;

(2) Unlocking the account

Sql>alter user stu account unlock;

(3) Termination password

In order to allow the user to change the password periodically, you can use the command to complete the termination password, as well as the DBA identity to the operation to create a profile file, requiring the user every 10 days to modify the login password, grace period 2 days

sql>create profile stu limit password_life_time Password_grace_time 2;

Sql>alter user Stu Profile Stu;

Unlock the same way

(4) Password history

If you want the user to change the password, you can use the password history, so that Oracle will store the password modification information in the data dictionary, so that when the user modifies the password, Oracle will compare the new password with the same, if prompted the user to re-enter.

For example:

sql>create profile password_history limit password_life_time password_grace_time 2 password_reuse_time 10

Sql>alter user Stu Profile password_history;

Password_reuse_time 10 means the password can be reused after 10 days

(5) Delete profile

Drop Profile password_history [cascade]

Cascade indicates that if you have already assigned a profile to a user, you still want to delete it, add cascade

Management of Tables

I. Naming conventions for table names and columns

1. Must start with a letter

2. Length cannot exceed 30 characters

3. Cannot use Oracle's reserved words

4. Use only the following string, a-->z,a-->z,0-->9,$, #等

II. data types supported by Oracle

1, character type

Char fixed length, maximum 2000 characters

For example: char (10) stores the contents as "Xiao Han", the first 4 characters descriptors ' Xiao Han ', the last six bits are filled with blanks

The advantages are: high efficiency, fast query rate. A field such as an ID can be set to char (18).

VARCHAR2 up to 4000 characters long (Oracle recommends it)

VARCHAR2 (10) Oracle allocates 4 characters when storing content as "Korean"

CLOB (character large object) character type large objects

4G Max

2. Number Type

Number Range-10 of 38 parties to 10 of 38 times

Can be an integer, or it can be a decimal

Number (5,2) indicates that a decimal has 5 significant digits and 2 bits is a decimal

For example: Define a range in -999.99-999.99 numbers can be used with number (5,2)

Define a range in-99999-99999 can be used number (5)

3. Date type

Date contains date and time of day and seconds

Timestamp Oracle extensions to date types

4. Picture type

Blob binary data, can store pictures, audio, video Max 4G

This type allows us to store large files in the database, but generally in the database, should be stored in the path of these files, if the security requirements, you can put files into the database

Third, build the table statement

1) Build Table

Sql>create Table Student (--table name

Idnumber (4),--School number

Namevarchar (20),--Name

Sex char (2),--gender

Birthday date);--Birthdate

The above statement is enough to create a simple student table

2) Add a field to an already established table

Sql>alter Table Student Add (ClassId number (2));

3) Modify the length of the field

Sql>alter table Studentmodify (Name varchar2 (50));

4) Modify the type/or name of the field (cannot have data)

Sql>alter Table Student Modify (Name char (20));

Sql>alter Table Student Rename Name to Sname;

5) Delete a field (use cautiously)

ALTER TABLE student drop column Sex;

6) Modify the name of the table

Sql>rename student to Stu;

7) Delete Table

drop table student;

8) View table structure

DESC student;

Iv. Operation table

1. Add data, all fields must be inserted

INSERT into student values (1, ' Zhang San ', ' Male ', ' January-May-05 ');

Don't think this is wrong, Oracle's default date format ' Dd-mon-yy ' (Day-month-year)

You can do this by changing the default format of the date

Sql>alter session Set nls_date_format= ' YYYY-MM-DD ';

You can add a type in a format that is familiar to us after you modify it.

INSERT into student values (1, ' Zhang San ', ' Male ', ' 2000-08-31 ');

But the changes here are only temporary, to change the date input format to be permanent changes to the registry, there is another way is to use the function, for the time being skipped

2. Insert a partial field, provided that the non-inserted field is allowed to be null

INSERT into student (Id,name) VALUES (1, ' Zhang San ');

3. Insert Null value

INSERT into student (Id,name,sex) VALUES (' 1 ', null,null);

4, the query name is empty a record

According to normal logic, a lot of people would do that.

SELECT * from Studentwhere name=null;

But the result is nothing, the correct method is as follows

SELECT * FROM student where Name is null;

Query all non-empty just add not after IS

5. Modify a field

Update student set sex= ' female ' where id= ' 1 ';

6. Modify multiple fields

Update student set sex= ' Male ', Name= ' Zhao Four ' whereid= ' 1 ';

7. Modify fields that contain null values

Update student set Name= ' Zhang San ' where Name is null;

8. Delete data (three ways)

1) Delete a record

Delete from student where id= ' 1 ';

2) Delete all records, the table structure is still in, the log will be recorded, the deletion can be restored, the speed will be slightly slower

Delete from student;

3) Delete the structure and data of the table

drop table student;

4) Delete all records, the table structure is still in, do not record the diary, all such deletions can not retrieve data, but fast

TRUNCATE TABLE student;

9. Recovering data

Data can be restored with delete from student

1) First set up a save point

SavePoint Sp;--sp is the name of the savepoint, can be arbitrarily named, the role is to save the data in the log

2) Delete data

Delete from student;

3) Query verification data is deleted

SELECT * from student;

The result is yes, no data

4) Rollback data

Rollback to SP;

5) Verify that the data rollback is successful in the query

SELECT * from student;

The results are still positive data back!

Of course, you can set multiple savepoint, but if you don't, the new savepoint will overwrite the previous savepoint by default.

10. Cancel Duplicate rows

SELECT distinct deptno,job from EMP;

Omit duplicate data by adding distinct to the Select after query

Oracle's BASIC Queries

First, we introduce two commands in PL/SQL software

1. Clear the screen command

Clear

2. Turn off/turn on show Operation Time Command

Set Timing off/on

Second, there are two SQL tips

1. Quickly insert large amounts of data into the database

Insert into users (Userid,username,userpass)

select * from user;

This statement is used only if there is at least one piece of data in the table

2. Query the number of records

Select COUNT (*) from user;

It is important to note that when writing SQL statements, you should be aware of the case.

Orace fields are case-insensitive and entities are case-sensitive

I. Using an arithmetic expression

? Show annual salary for each employee

You can use the alias of a column

Select Ename "Name", sal*12 as "annual income" from EMP;

It is best to use quotation marks in Chinese, try not to use Chinese

? If there is a null value in the calculation expression then the result is null, how to handle the null value?

Using the NVL function to handle

Select SAL*13+NVL (comm,0) "annual salary", ename from EMP;

NVL (comm,0) means that if Comm is null, it is calculated by 0, not 0 by itself

? How to connect strings

Use "| |"

Select Ename | | ' is a ' | | Job from EMP;

Second, use the WHERE clause

? How to show employees with wages above 3000

Select Ename,sal from emp where Sal >3000;

How to find employees who have been in employment since 1982.1.1

Select ename from emp where hiredate> ' January-January-1982 ';

? Find employees with wages between 2000-2500

Select ename from emp where sal>=2000 and Sal <=2500;

Third, how to use the LIKE operator

%: represents 0 to more characters

_: Represents any single character

? How to display an employee with the first letter S

Select ename from emp where ename like ' s% ';

? How to display the names and wages of all employees with a third letter in uppercase O

Select Ename, Sal from the EMP where ename like ' __o% ';

Iv. using in in the Where condition

How do i show an employee with a empno of 123,456,234?

SELECT * from EMP where empno in (123,234,456);

This query is highly efficient

V. Using the IS NULL operator

? How to show an employee without a superior

SELECT * from emp where Mgr is null;

Vi. use of logical operation symbols

Query for employees whose wages are higher than 500 or who are manager of the job, and also to meet their first and last name uppercase T

SELECT * from emp where (sal>500 or job= ' MANAGER ') and ename like ' t% ';

The parentheses here cannot be forgotten, otherwise the condition is changed because the and priority is higher than or

Vii. using the ORDER BY clause

How to show employees in the order of wages from highest to lowest

Select ename from emp order by Sal Desc;

Desc to reverse ASC to order (default)

? In descending order of employee wages in ascending order of department number

SELECT * from emp ORDER by DEPTNO Asc,sal desc;

Eight, sort by using the alias of the column

Select Ename, sal*12 "annual salary" from the emp Order BY "annual salary" ASC;

Oracle Basic Knowledge

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.