I am participating in the CSDN "new programmer" award-winning essay solicitation
There are thousands of people in the vast sea. Thank you for seeing here this second. I hope my article will help you!
May you keep your love and go to the mountains and seas in the future!
1. Basic knowledge of database
1.1 why learn database
First of all, we need to know how many ways we save data?
-
The data is stored in memory
There are ways to save in memory: collection and array.
int[] arr = new int[]{1, 2, 3, 4}; ArrayList<Integer>list = new ArrayList<Integer>(); list.add(1); list.add(2);
new objects are stored in the heap, which is a small space in memory.
Advantages: fast memory speed.
Disadvantages: when the power is off / the program exits, the data will be cleared, and it is not guaranteed to save the data permanently. -
The data is saved in a normal file
Advantages: permanent storage
Disadvantages: it is troublesome and inefficient to find, add, modify and delete dataLet's see the photo files I have treasured for many years.
-
The data is saved in the database
advantage:-
Permanent storage to achieve data persistence.
-
Use a complete management system for unified management and easy query. It is more convenient to operate the database through SQL statements. The database is an efficient solution to manage a large amount of information
-
You can see the benefits of using a database:
- Persistent data to local.
- It can realize structured query and facilitate management.
1.2 concept of database
- DB: database, warehouse for storing data. It holds a series of organized data.
- DBMS: database management system, also known as database software (product). Database is a container created and operated by DBMS, which is used to manage data in DB.
- SQL: structured query language, which is specially used to communicate with database, that is, the language used to communicate with DBMS.
1.3 characteristics of data stored in database
-
The database storage method is to put the data into the table, and then put the table into the database.
-
There can be multiple tables in a database. Each table has a name to identify itself. Table names are unique.
-
Tables have some features that define how data is stored in tables, similar to the design of classes in Java.
-
A table consists of columns, which we also call fields. All tables are composed of one or more columns, and each column is similar to an attribute in Java
-
The data in the table is stored in rows, and each row is similar to an object in Java.
1.4 common databases
-
Oracle: a large database charged by Oracle company. Oracle acquired SUN and MySQL.
-
MySQL: open source free database, small database. Has been acquired by Oracle.
-
DB2: IBM's database product, for a fee. It is often used in banking system.
-
SQL Server: a medium-sized database charged by MicroSoft. C#,. net and other languages are often used.
-
SyBase: it has faded out of the historical stage. PowerDesigner provides a very professional data modeling tool.
-
SQLite: a small embedded database, which is applied on the mobile terminal.
Oracle and MySQL are the most commonly used databases on the Internet.
MySQL database is used most in Web applications for the following reasons:
- Open source, free. The most important is free, which is also the database we focus on learning now.
- Powerful enough to cope with Web application development (up to 10 million levels of concurrent access).
1.5 database uninstallation and installation
1.5.1 MySQL directory structure
Just know the directory structure:
│-- bin: mysql Related executable files*.exe │-- MySQLInstanceConfig.exe mysql Configuration program for │-- data: mysql Self contained database file(Don't pay attention) │-- include: c Language header file(Don't pay attention) │-- lib: deposit mysql Used dll Dynamic library(amount to jar Package, don't pay attention) │-- my.ini mysql Configuration file for,Configured mysql Information about
1.5.2 start and stop of MySQL service
There are two ways to start and stop MySQL services:
-
Computer -- > right click management -- > Service
Right click here to start or stop the MySQL service.
-
Enter the DOS command line through cmd and enter:
net start mysql Start service net stop mysql Shut down service
1.5.3 login and exit MySQL server
MySQL is a database that requires an account name and password to log in. After logging in, it provides a default root account. We set the password when using and installing. This account and password are the super user administrator. Just log in directly.
-
Method 1: enter mysql -u user name - p password on the DOS command line
**Note: there is no space after * * u and p.
-
Method 2: enter mysql -hip address - u user name - p password on the DOS command line
-
How to exit MySQL: exit or quit
The above two logins have also been demonstrated.
1.6 relationship between server and database, table and record
- A database is a folder
- A table represents a file
- Records represent data
2. MySQL basic syntax
2.1 classification and syntax of SQL statements
1. What is SQL
Structured query language (SQL for short). A language designed to communicate with a database.
2. Function
-
Through SQL statements, we can easily operate databases, tables and data.
-
SQL is a standard that database management systems need to follow. Different database manufacturers support SQL statements, but they all have unique contents.
3. Classification
The more important ones are DML and DQL. Is to add, delete, modify and check.
4. Specifications
- The SQL statements of MySQL database are not case sensitive, but it is recommended that keywords be capitalized and table names and column names be lowercase.
- SQL statements can be written in one or more lines, ending with a semicolon, that is, it is best to end each command with a semicolon
- Each command can be indented or wrapped as needed to enhance readability.
- notes:
- SQL specific single line comment: # comment text
- Single line note: - note text
- Multiline note: / * note text*/
3. DCL language learning
It is mainly used to operate the user's permissions. Mainly understand.
By default, we use the super administrator user brought during MySQL installation: root user, with all permissions. However, the database server in a company may run databases of many projects at the same time. Therefore, we should be able to establish different users according to different projects and assign different permissions to manage and maintain the database.
1. Create user
-
Syntax:
CREATE USER 'user name'@'host name' IDENTIFIED BY 'password';
Explanation:
- User name: the user name that will be created
-
Host name: specify the host on which the user can log in. If it is a local user, localhost can be used. If you want the user to log in from any remote host, you can use the wildcard%
- Password: the login password of the user. The password can be blank. If it is blank, the user can log in to the server without a password
Demonstrate:
-- user1 Users can only localhost this IP Sign in mysql The server CREATE USER 'user1'@'localhost' IDENTIFIED BY '123'; -- user2 Users can log in on any computer mysql The server CREATE USER 'user2'@'%' IDENTIFIED BY '123';
2. Authorized user
After the user is created, unlike the root super administrator, it basically has no permissions! User authorization is required.
-
Syntax:
GRANT Authority 1, Authority 2... ON Database name.Table name TO 'user name'@'host name';
Explanation:
-
GRANT authorization keyword.
- Permissions granted to users, such as SELECT, INSERT, UPDATE, etc. Use ALL if you want to grant the required permissions.
-
Database name Table name: which tables of which database the user can operate. If you want to grant the user corresponding operation permissions on all databases and tables, it can be represented by * such as *. *.
- 'user name' @ 'host name': which user is authorized.
In the demo, assign user1 the permission to test this database operation:
GRANT CREATE,ALTER,DROP,INSERT,UPDATE,DELETE,SELECT ON test.* TO 'user1'@'localhost';
3. Revocation of authorization
-
grammar
REVOKE Authority 1, Authority 2... ON Database name.Table name FROM 'user name'@'host name';
Explain:
- REVOKE keyword.
Under the demonstration, revoke the permission of user1 user to test operation
REVOKE ALL ON test.* FROM 'user1'@'localhost';
4. View permissions
-
Syntax:
SHOW GRANTS FOR 'user name'@'host name';
Under the demo, view the permissions of user1 user:
SHOW GRANTS FOR 'user1'@'localhost';
5. Delete user
-
Syntax:
DROP USER 'user name'@'host name';
Under the demo, delete user2:
DROP USER 'user2'@'%';
6. Change password
You need to operate without logging in to MySQL. And need to know the original password.
-
grammar
mysqladmin -uroot -p Old password password New password -- New passwords don't need quotes
Demonstrate:
mysqladmin -uroot -p123 password 123456
4. Learning DDL language
Library and table management.
1. Library management
1.1 create database
Since we all have MySQL, right? We have to CREATE our own database. How do we CREATE it? The keyword created here is: CREATE.
CREATE DATABASE Database name;
You can directly create the database, but if you are not sure whether the database exists, is it necessary to create it, and an error will be reported if you create it again, then you need a keyword: IF NOT EXISTS to judge whether it does not exist.
CREATE DATABASE IF NOT EXISTS Database name;
During the creation process, we can also specify a character set to the database. The default character set is UTF-8.
CREATE DATABASE Data name DEFAULT CHARACTER SET character set;
Direct demonstration:
CREATE DATABASE stu; CREATE DATABASE IF NOT EXISTS stu; CREATE DATABASE stu2 CHARACTER SET gbk;
1.2 viewing database
Now that the database has been created, how should we view it? The keyword to view here is: SHOW.
-
View all databases
SHOW DATABASES;
-
You can also view our definition information for a database
SHOW CREATE DATABASE Data name;
Demonstrate:
SHOW DATABASES; SHOW CREATE DATABASE stu2;
1.3 modifying and deleting databases
-
Modify database character set
Modified keyword: ALTER.
ALTER DATABASE Database name DEFAULT CHARACTER SET character set;
For direct demonstration, change the gbk character set of the stu2 database just set to uft8.
ALTER DATABASE stu2 DEFAULT CHARACTER SET utf8;
-
Delete database
Keywords deleted: DROP.
DROP DATABASE Database name;
Generally, we don't know whether the database exists or not, so we can add IF EXISTS to judge whether it exists.
DROP DATABASE IF EXISTS Database name;
Under the demonstration, delete the stu2 database. Hey, hey, it's impossible to delete the database and run away.
DROP DATABASE stu2; SHOW DATABASES;
1.4 using database
-
We can now see what the database is in use
SELECT DATABASE();
-
Next, you can use / switch the database to create tables or add, delete, modify and query tables in the future.
USE Database name;
Demonstrate:
SELECT DATABASE(); USE stu; SELECT DATABASE();
1.5 summary
DDL statement operation database | keyword |
---|---|
establish | CREATE DATABASE database name; |
modify | ALTER DATABASE database name DEFAULT CHARACTER SET character set; |
see | SHOW DATABASES; |
delete | DROP DTABASE database name; |
2. Table management
Note: before using a table every time, you must first use a database to make sure you are in that database!
2.1 creating tables
After we CREATE the database, it is equivalent to creating a folder, so we need to CREATE a file that can save the data, right? Next, let's CREATE a table. Keywords created: CREATE.
CREATE TABLE Table name (Field name 1 field type 1, Field name 2 field type 2);
Do you think it's not nice to write like this? It's mentioned above that in the SQL specification, you can indent or wrap lines appropriately to increase readability:
CREATE TABLE Table name ( Field name 1 field type 1, Field name 2 field type 2 );
Moreover, if we cannot judge whether the table exists, we can also use the keyword IF NOT EXISTS to judge whether it does not exist.
CREATE TABLE IF NOT EXISTS Table name (Field name 1 field type 1, Field name 2 field type 2);
The field name is our name. What are the field types:
-
Common data types of MySQL include:
- int: integer.
- double: floating point type.
- varchar: string type.
- Date: date type. Only year, month and day, no hours, minutes and seconds. "yyyy-MM-dd".
-
The detailed data types are as follows:
-
Integer:
-
String type:
-
Date and time type
-
Show me how to create a table:
CREATE TABLE student ( id INT, name VARCHAR(20), birthday DATE );
Later, I will directly use SQLyog to demonstrate. After all, the DOS command is not as convenient as the image client.
If you don't have SQLyog installed, you can go to the above. I teach you how to install MySQL. Generally, if you follow it all, you will have it. If you still want DOS command to train, of course I have no objection. hey! come on.
2.2 view table
Now that we have created the table, let's see what table we have created, right. Keywords to view: SHOW, DESC.
-
View all tables in the database we are using:
SHOW TABLES;
-
By viewing the table structure, you can see the data types and fields when we create the table:
DESC Table name;
-
To view the SQL statement that created the table:
SHOW CREATE TABLE Table name;
The demonstration is as follows:
SHOW TABLES; DESC student; SHOW CREATE TABLE student;
More convenient, I still use DOS command to demonstrate more simply.
2.3 copy table
Copying a table without copying the data content is equivalent to copying the table structure.
CREATE TABLE Table name LIKE Other tables;
Demonstrate:
CREATE TABLE s1 LIKE student; SHOW TABLES; DESC s1 ;
2.4 delete table
Delete table directly
DROP TABLE Table name;
If you cannot determine whether the table name exists, you can use the keyword IF EXISTS to determine whether it exists.
DROP TABLE IF EXISTS Table name;
Demonstrate:
SHOW TABLES; DROP TABLE s1; SHOW TABLES; DROP TABLE s1; DROP TABLE IF EXISTS s1;
2.5 modification table
Generally speaking, when we create a table, we don't need to modify it much, but there are always requirements. Modified keyword: ALTER. The modified statements are generally ALTER TABLE table table name xxx.
-
ADD a column of the table and ADD the keyword ADD.
ALTER TABLE Table name ADD Field name field type;
Demo: add an age and a column of type int in the student table.
ALTER TABLE student ADD age INT; DESC student;
-
MODIFY the field type and add the keyword MODIFY.
ALTER TABLE Table name MODIFY Field name new type;
For example, change the name field in the student table to varchar(10).
ALTER TABLE student MODIFY name VARCHAR(10); DESC student;
-
Modify the field name, keyword: CHANGE.
ALTER TABLE Table name CHANGE Old field name new field name type;
For example, change the name field in the student table to sName, and the type is varchar(20).
ALTER TABLE student CHANGE NAME sName VARCHAR(20); DESC student;
-
Delete field, delete keyword: DROP.
ALTER TABLE Table name DROP Field name;
Under demonstration, delete the field age in the student table.
ALTER TABLE student DROP age; DESC student;
-
Modify the table name, that is, RENAME the table name. Keyword: RENAME.
RENAME TABLE Table name TO New table name;
For example, rename the student table to the student2 table.
RENAME TABLE student TO student2; SHOW TABLES;
-
Modify the character set of the table. No character set is set. The default is utf8.
ALTER TABLE Table name DEFAULT CHARACTER SET New character set;
For example, change the encoding of the student2 table to GBK >.
ALTER TABLE student2 DEFAULT CHARACTER SET gbk;
2.6 summary
DDL statement operation table | keyword |
---|---|
establish | CREATE TABLE table name; |
modify | ALTER TABLE table name xxx; |
see | SHOW TABLES; |
delete | DROP TABLE name; |
5. Learning DML language
It mainly adds, deletes and modifies the data in the table.
First create a beauty table, which contains the fields id, name, sex, birthday and phone.
CREATE TABLE beauty( id INT, NAME VARCHAR(20), sex CHAR(2), birthday DATE, phone VARCHAR(15) );
In this way, the table is created first, and the next operation is to operate on it.
In the following learning, the table is updated. Now we haven't learned the query statement. Let's teach you to view all the data in the table first:
SELECT * FROM beauty;
1. Insert data
There are two insertion methods. We learn one by one:
Insert keyword: INSERT INTO.
1.1 first insertion method
-
Insert all fields
-
Write out all field names:
INSERT INTO Table name (Field name 1, Field name 2, Field name 3, ...) VALUES (Value 1, Value 2, Value 3, ...);
-
If you add field values in the original order, you can add data directly without writing the field name:
INSERT INTO Table name VALUES (Value 1, Value 2, Value 3, ...);
-
-
Insert partial data
You only need to specify the field to insert data, and you can change the position at will, but the field value corresponds to the type of column. If there is no field to add data, NULL will be used:
INSERT INTO Table name (Field name 1, Field name 2...) VALUES (Field value 1, Field value 2);
-
The above SQL statements demonstrate the following one by one:
-
Write all field names.
INSERT INTO beauty (id, NAME, sex, birthday, phone) VALUES(1, "Tang Yixin", 'female', "1987-10-9", "1899888823"); SELECT * FROM beauty;
-
Moreover, the type of the inserted value here must be consistent or compatible with the type of the column.
INSERT INTO beauty (id, NAME, sex, birthday, phone) VALUES(2, Tang Yixin, female, "1987-10-9", 1899888823);
-
Do not write field names. And columns that can be NULL values can be inserted with NULL.
INSERT INTO beauty VALUES (2, "Delireba", 'female', "1992-6-3", "1899888824"), (3, "Gulinaza", 'female', "1992-5-2", NULL); SELECT * FROM beauty;
-
Insert partial data. If there is no field to insert data, it will be displayed as the default value, and if no default value is set, it will be NULL.
INSERT INTO beauty (id, NAME, sex) VALUES(4, "Yang Mi", 'female'); SELECT * FROM beauty;
-
-
characteristic:
- The field type and value type are consistent or compatible, and the number and type of one-to-one correspondence are the same.
- You can not write some field names. It is NULL by default when adding, unless the default value is set.
1.2 second insertion method
Compared with the first, the syntax is simpler.
-
Syntax:
INSERT INTO Table name set field=value, Field 2=Value 2,...;
-
Application:
Add a new piece of data:
INSERT INTO beauty SET id=5, NAME='Zhuge Dali', sex='female', birthday='1995-05-23'; SELECT * FROM beauty;
1.3 comparison of the two methods
-
Mode 1 supports multi line insertion, while mode 2 does not.
INSERT INTO beauty VALUES (6, 'Loura ', 'female', '1988-12-27', '16689540123'), (7, 'Mei Jia Chen', 'female', '1985-11-21', '16689540123'), (8, 'Liu Mengmeng', 'female', '1990-10-16', '16689540123'); SELECT * FROM beauty;
-
Method 1 supports sub queries (described in detail later), while method 2 does not.
INSERT INTO beauty (id, NAME , sex ,birthday) SELECT 9, 'Zhao Wen', 'female', '1987-10-28'; SELECT * FROM beauty;
Therefore, the insertion method of mode 1 is used more.
1.4 data garbled in DOS command window
We are now operating data in SQLyog software. Its own character set corresponds to the character set of MySQL server, so there will be no garbled code. However, when we use DOS command line for SQL statement operation, if there is Chinese, there will be garbled code, resulting in SQL execution failure.
Specific causes:
-
Because the MySQL client setting code is utf8, and the DOS command line code of the system is gbk, the code is inconsistent, resulting in garbled code.
How to solve it:
-
On the DOS command line, enter: set names gbk; Let the server use gbk encoding now.
Note: the above method is a temporary scheme. It will become invalid after exiting the DOS command line. It needs to be configured every time.
-
Modify my. In the MySQL installation directory INI file, restart the service and take effect everywhere. This scheme modifies all codes, so it is not recommended.
2. Modify and update data
Modify the keyword of the table: UPDATEA.
-
We can modify the data without conditions, which is equivalent to modifying all the field names.
UPDATE Table name SET Field name=field value;
-
You can also modify the data with conditions, which is equivalent to modifying the field name of the row found only after the WHERE condition.
UPDATE Table name SET Field name=field value WHERE condition;
The summary grammar can be written as follows:
UPDATE Table name SET Field name=Field value[ WHERE Conditions]; []The representative can be written or not.
-
The specific operation is as follows:
-
Modify the data without conditions and change all genders to men. Of course, how can goddesses be men? I'll revise it later.
UPDATE beauty SET sex = 'male'; SELECT * FROM beauty; UPDATE beauty SET sex = 'female';
-
Modify the data conditionally, and change the goddess name with id No. 5 to achievement. In fact, Zhuge Dali's real name is the result.
UPDATE beauty SET NAME = 'achievements' WHERE id = 5; SELECT * FROM beauty;
-
Modify multiple columns at a time, change the goddess name with id No. 5 to Zhuge Dali, and change the phone to 155673412312.
UPDATE beauty SET NAME = 'Zhuge Dali', phone = '155673412312' WHERE id = 5; SELECT * FROM beauty;
-
3. Delete data in the table
There are two ways to delete:
- The first keyword: DELETE. You can filter with WHERE.
- The second keyword: TRUNCATE. You cannot filter with WHERE. Directly delete all data in the table.
3.1 first deletion method
-
Delete the data with WHERE filter criteria and delete the data that meets the criteria.
DELETE FROM Table name WHERE condition;
-
Deleting data without WHERE filter criteria is directly equivalent to deleting all data in the table. Hey, hey, it's really exciting to delete tables, delete libraries and run away.
DELETE FROM Table name;
-
Specific demonstration:
-
Delete data with conditions and delete the record with id 9
DELETE FROM beauty WHERE id = 9; SELECT * FROM beauty;
-
Can you delete multiple records:
DELETE FROM beauty WHERE id = 8, id = 7; This will definitely not work, and an error will be reported: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' id = 7' at line 1 So you can do this: DELETE FROM beauty WHERE id IN (7, 8); SELECT * FROM beauty;
-
Delete the data without conditions and delete all the data in the table. I have a backup of the table here. You can see my operation. Is it not good to delete it after learning the backup later, or do you still want to add it.
DELETE FROM beauty; SELECT * FROM beauty;
-
3.2 the second deletion method
Compared with the first, it is more violent and can only delete all the data. Is it violent.
-
Syntax:
TRUNCATE TABLE Table name;
-
Application:
TRUNCATE TABLE beauty; SELECT * FROM beauty;
3.3 large PK in two ways
-
TRUNCATE cannot add a WHERE condition, but DELETE can add a WHERE condition.
-
TRUNCATE is a little more efficient.
It is well understood that the TRUNCATE cannot add the WHERE condition, so the execution efficiency is faster than that of DELETE.
-
TRUNCATE deletes a table with self growing columns. If data is inserted again, the data starts from 1.
After deleting a table with self growing columns, if you insert data again, the data will start from the last breakpoint, that is, the self growing column position before the last deletion will reach 1000. Whether all or some are deleted, the next addition will start from 1001. The self growth column will be explained later.
-
TRUNCATE has no return value, while DELETE has a return value.
We execute the following commands:
DELETE FROM beauty WHERE id > 5; TRUNCATE TABLE beauty;
-
TRUNCATE deletion cannot be rolled back. DELETE deletion can be rolled back. This rollback is reflected in the transaction, which will be explained later. Don't panic!
4. Summary
DML statement operation table | keyword |
---|---|
insert | The first type: INSERT INTO table name (field 1, field 2...) values (field value 1, field value 2...); The second type: INSERT INTO table name, SET field 1 = field value 1, field 2 = field value 2; |
modify | UPDATE table name: SET field 1 = field value 1, field 2 = field value 2... [WHERE filter criteria]; |
delete | The first type: DELETE FROM table name [WHERE filter criteria]; The second type: TRUNCATE TABLE table name; |
6. Closure
I'm sure you'll understand MySQL here. Of course, it hasn't been involved yet. Due to space constraints, I'll put the query in the next article. Query is still very important to us. For junior programmers, the most used is query statements.
In our practical application, MySQL still accounts for a very large mainstream. Today, we know a basic series of MySQL, which will be helpful for some advanced applications and tuning in the future. And MySQL is often asked in the interview, so MySQL learning is also essential!
Let's make a brief summary:
DCL: It is mainly used to operate the user's permissions Create user: CREATE USER 'user name'@'host name' IDENTIFIED BY 'password'; Authorized user: GRANT Authority 1, Authority 2... ON Database name.Table name TO 'user name'@'host name'; Revocation of authorization: REVOKE Authority 1, Authority 2... ON Database name.Table name FROM 'user name'@'host name'; View permissions: SHOW GRANTS FOR 'user name'@'host name'; Delete user: DROP USER 'user name'@'host name'; DDL: Library and table management. Create database: CREATE DATABASE Database name; Create table: CREATE TABLE Table name (Field name 1 field type 1, Field name 2 field type 2); Modify database: ALTER DATABASE Database name DEFAULT CHARACTER SET character set; Modify table: ALTER TABLE Table name some operations; Delete database: DROP DATABASE Database name; Delete table: DROP TABLE Table name; DML: It mainly adds, deletes and modifies the data in the table. Insert data: INSERT INTO Table name (Field name 1, Field name 2, Field name 3, ...) VALUES (Value 1, Value 2, Value 3, ...); Modify data: UPDATE Table name SET Field name=field value; Delete data: DELETE FROM Table name;
Of course, more details of sentence commands, I hope you can study them carefully!
Learn here, today's world is closed, good night! Although this article is over, I am still there and will never end. I will try to keep writing articles. The future is long. Why are you afraid of cars and horses!
Thank you for seeing here! May you live up to your youth and have no regrets!
Note: if there are any mistakes and suggestions in the article, please leave a message! If this article is also helpful to you, I hope you can pay attention to it. Thank you very much!