当前位置:网站首页>MySQL common commands
MySQL common commands
2022-06-09 08:40:00 【weixin_ forty-six million seven hundred and eighty-seven thousa】
The most common display command :
1、 Show database list .
show databases;
2、 Display the data table in the library :
use mysql;
show tables;
3、 Show the structure of the data table :
describe Table name ;
4、 Building database :
create database Library name ;
5、 Build table :
use Library name ;
create table Table name ( Field setting list );
6、 Delete database and table :
drop database Library name ;
drop table Table name ;
7、 Empty the records in the table :
delete from Table name ;
8、 Show the records in the table :
select * from Table name
Connect MySQL
Format : mysql -h The host address -u user name -p User password
example 1: Connected to the MySQL.
mysql -uroot -pmysql;
Connect to... On the remote host MYSQL.
mysql -h 127.0.0.1 -uroot -pmysql;
2、 Connect to... On the remote host MYSQL. Suppose the remote host's IP by :110.110.110.110, The user is called root, The password for abcd123. Then type the following command :
mysql -h110.110.110.110 -u root -p 123;( notes :u And root You don't need to add spaces between them , So are the others )
3、 sign out MYSQL command : exit ( enter )
Change new password
Input... At the terminal :mysql -u user name -p password , Enter by car Mysql.
use mysql;
update user set password=PASSWORD(‘ New password ’) where user=‘ user name ’;
flush privileges; # Update the permissions
quit; # sign out
Two 、 Change Password .
Format :mysqladmin -u user name -p Old password password New password
1、 to root Add a code ab12. First, in the DOS Go down to the directory mysql\bin, Then type the following command
mysqladmin -u root -password ab12
notes : Because at the beginning root No password , therefore -p The old password can be omitted .
2、 then root The password of is changed to djg345.
mysqladmin -u root -p ab12 password djg345
( Be careful : Different from the above , The next reason is MYSQL Commands in the environment , So it's followed by a semicolon as the command Terminator )
3、 Command line modification root password :
mysql> UPDATE mysql.user SET password=PASSWORD(’ New password ’) WHERE User=’root’;
mysql> FLUSH PRIVILEGES;
4、 Show current user:
mysql> SELECT USER();
3、 ... and 、 Add new users .
Format :grant select on database .* to user name @ Log on to the host identified by “ password ”
1、 Add a user test1 The password for abc, Let him log on to any host , And query all databases 、 Insert 、 modify 、 Delete permissions . First use root User connection
MYSQL, Then type the following command :
grant select,insert,update,delete on . to test1”%" Identified by “abc”;
But increasing the number of users is very dangerous , You want to know as someone test1 Password , Then he can be in internet Log in to your... On any computer on mysql Database and do whatever you want with your data , See... For the solution 2.
2、 Add a user test2 The password for abc, Let him only be in localhost On the login , And it can be used for database mydb The query 、 Insert 、 modify 、 Deleted actions (localhost Refers to the local host , namely MYSQL The host where the database is located ),
In this way, the user can use it to know test2 Password , He can't go from internet Direct access to the database , Only through MYSQL Host computer web Page came to visit .
grant select,insert,update,delete on mydb.* to [email protected] identifiedby “abc”;
If you don't want to test2 Password , You can type another command to erase the password .
grant select,insert,update,delete on mydb.* to [email protected] identified by “”;
Delete user
mysql -u user name -p password
mysql>delete from user where user=‘ user name ’ and host=‘localhost’;
mysql>flush privileges;
// Delete user's database
mysql>drop database dbname;
Database operation
Show all databases
mysql> show databases;( Be careful : The last one s)
Create database
mysql> create database test;
Connect to database
mysql> use test;
View currently used databases
mysql> select database();
Table information contained in the current database
mysql> show tables; ( Be careful : The last one s)
Delete database
mysql> drop database test;
Table operations
remarks : Use before operation “use < Database name >” You should connect to a database .
Build table
command :create table < Table name > (< Field name 1> < type 1> [,…< Field name n> < type n>]);
Example :
mysql> create table MyClass(
id int(4) not null primary key auto_increment,
name char(20) not null,
sex int(4) not null default ‘0’,
degree double(16,2));
Get table structure
command : desc Table name , perhaps show columns from Table name
Example :
mysql> describe MyClass
mysql> desc MyClass;
mysql> show columns from MyClass;
Delete table
command :drop table < Table name >
for example : Delete table name MyClass Table of
mysql> drop table MyClass;
insert data
command :insert into < Table name > [( < Field name 1>[,…< Field name n > ])] values ( value 1 )[, ( value n )]
Example :
mysql> insert into MyClass values(1,‘Tom’,96.45),(2,‘Joan’,82.99), (2,‘Wang’, 96.59);
Query data in table
Query all lines
mysql> select * from MyClass;
Query the first few lines of data
for example : See the table MyClass Middle front 2 Row data
mysql> select * from MyClass order by id limit 0,2;
perhaps
mysql> select * from MyClass limit 0,2;
Delete data in table
command :delete from Table name where expression
for example : Delete table MyClass Number is 1 The record of
mysql> delete from MyClass where id=1;
Modify the data in the table
command :update Table name set Field = The new value ,… where Conditions
mysql> update MyClass set name=‘Mary’ where id=1;
Add fields... To the table
command :alter table Table name add Field type other ;
for example : In the table MyClass Added a field to passtest, The type is int(4), The default value is 0
mysql> alter table MyClass add passtest int(4) default ‘0’
Change table name
command :rename table Original table name to The new name of the table ;
for example : In the table MyClass Change the name to YouClass
mysql> rename table MyClass to YouClass;
Update field content
command :update Table name set Field name = New content
update Table name set Field name = replace( Field name , ‘ Old content ’, ‘ New content ’);
for example : In front of the article, add 4 A space
update article set content=concat(’ ', content);
Database import and export
Export database file from database
Use “mysqldump” command
First of all to enter DOS Interface , Then do the following .
1) Export all databases
Format :mysqldump -u [ Database user name ] -p -A>[ Save path of backup file ]
2) Export data and data structures
Format :mysqldump -u [ Database user name ] -p [ The name of the database to back up ]>[ Save path of backup file ]
give an example :
example 1: Will database mydb Export to e:\MySQL\mydb.sql In file .
Open up and start -> function -> Input “cmd”, Enter command line mode .
c:> mysqldump -h localhost -u root -p mydb >e:\MySQL\mydb.sql
Then enter the password , After a while, the export is successful , You can go to the target file to check if it is successful .
example 2: Will database mydb Medium mytable Export to e:\MySQL\mytable.sql In file .
c:> mysqldump -h localhost -u root -p mydb mytable>e:\MySQL\mytable.sql
example 3: Will database mydb The structure of is derived to e:\MySQL\mydb_stru.sql In file .
c:> mysqldump -h localhost -u root -p mydb --add-drop-table >e:\MySQL\mydb_stru.sql
remarks :-h localhost It can be omitted , It is generally used on virtual host .
3) Only export data, not data structure
Format :
mysqldump -u [ Database user name ] -p -t [ The name of the database to back up ]>[ Save path of backup file ]
4) Export... From the database Events
Format :mysqldump -u [ Database user name ] -p -E [ Database user name ]>[ Save path of backup file ]
5) Export stored procedures and functions in the database
Format :mysqldump -u [ Database user name ] -p -R [ Database user name ]>[ Save path of backup file ]
Import from an external file into the database
1) Use “source” command
First of all to enter “mysql” Command console , Then create the database , Then use the database . Finally, do the following .
mysql>source [ Save path of backup file ]
2) Use “<” Symbol
First of all to enter “mysql” Command console , Then create the database , And then quit MySQL, Get into DOS Interface . Finally, do the following .
mysql -u root –p < [ Save path of backup file ]
6、 ... and 、 Backup database :
Be careful ,mysqldump Command in DOS Of mysql\bin Execute under directory , Can't be in mysql Execution in environment , therefore , Cannot use semicolon “;” ending . If you have logged in mysql, Please run the exit command mysql> exit
1. Export the entire database
The export file exists by default mysql\bin Under the table of contents
mysqldump -u user name -p Database name > Exported file name
mysqldump -uroot -p123456 database_name > outfile_name.sql
2. Export a table
mysqldump -u user name -p Database name Table name > Exported file name
mysqldump -u user_name -p database_name table_name > outfile_name.sql
3. Export a database structure
mysqldump -u user_name -p -d –add-drop-table database_name > outfile_name.sql
-d No data –add-drop-table At every create Add a... Before the statement drop table
4. Export with language parameters
mysqldump -uroot -p –default-character-set=latin1 –set-charset=gbk –skip-opt database_name > outfile_name.sql
7、 ... and 、 Transfer text data to the database
1、 The text data should conform to the format : Use... Between field data tab Key separation ,null Value to use \n Instead of . example :
3 rose Dalian No.2 Middle School 1976-10-10
4 mike Dalian No.1 Middle School 1975-12-23
Suppose you save these two sets of data as school.txt file , Put it in c Under the root directory .
2、 Data in command
mysql> load data local infile “c:\school.txt” into table Table name ;
Be careful : You'd better copy the file to mysql\bin Under the table of contents , And use it first use The library where the command is printed .
8、 ... and 、 Operation of the watch
1、 Show the structure of the data table :
mysql> DESCRIBE Table name ; (DESC Table name )
2、 Create data tables :
mysql> USE Library name ; // Access to database
mysql> CREATE TABLE Table name ( Field name VARCHAR(20), Field name CHAR(1));
3、 Delete data table :
mysql> DROP TABLE Table name ;
4、 Rename the data table
alter table t1 rename t2;
5、 Show the records in the table :
mysql> SELECT * FROM Table name ;
6、 Insert a record into a table :
mysql> INSERT INTO Table name VALUES (”hyq”,”M”);
7、 Update the data in the table :
mysql-> UPDATE Table name SET Field name 1=’a’, Field name 2=’b’ WHERE Field name 3=’c’;
8、 Empty the records in the table :
mysql> DELETE FROM Table name ;
9、 Load data into a data table in text form :
mysql> LOAD DATA LOCAL INFILE “D:/mysql.txt” INTO TABLE Table name ;
10、 Definition of display table , You can also see the constraints of the table , For example, foreign key
mysql> SHOW CREATE TABLE yourtablename ;
You can also use mysqldump Dump the complete definition of the table to a file , Including, of course, foreign key definitions .
You can also list the tables through the following instructions T The foreign key constraint of :
mysql> SHOW TABLE STATUS FROM yourdatabasename LIKE ‘T’
Foreign key constraints will be listed in the table comments .
stored procedure
11、 Create stored procedure
CREATE PROCEDURE procedureName (in paramentName type, in paramentName type,……)
BEGIN
SQL sentences;
END
12、 Calling stored procedure
mysql> CALL procedureName(paramentList);
example :mysql> CALL addMoney(12, 500);
13、 View stored procedures for a specific database
Method 1 :mysql> SELECT name FROM mysql.proc WHERE db = ‘your_db_name’ AND type = ‘PROCEDURE’
Method 2 :mysql> show procedure status;
14、 Delete stored procedure
mysql> DROP PROCEDURE procedure_name;
mysql> DROP PROCEDURE IF EXISTS procedure_name;
15、 View the specified stored procedure definition
mysql> SHOW CREATE PROCEDURE proc_name;
mysql> SHOW CREATE FUNCTION func_name;
---------- Example 1 -----------
mysql> DELIMITER $$
mysql> USE db_name$$ // Select database
mysql> DROP PROCEDURE IF EXISTS addMoney$$ // If there is a stored procedure with the same name , Delete it
mysql> CREATE DEFINER= root@localhost PROCEDURE addMoney(IN xid INT(5),IN xmoney INT(6))
mysql> BEGIN
mysql> UPDATE USER u SET u.money = u.money + xmoney WHERE u.id = xid; // A semicolon ";" Will not cause the statement to execute , Because the current delimiter is defined as $$
mysql> END$$ // End
mysql> DELIMITER ; // Change the delimiter back to semicolon ";"
mysql> call addMoney(5,1000); // Execute stored procedures
---------- Example 2 -----------
mysql> delimiter //
mysql> create procedure proc_name (in parameter integer)
mysql> begin
mysql> if parameter=0 then
mysql> select * from user order by id asc;
mysql> else
mysql> select * from user order by id desc;
mysql> end if;
mysql> end;
mysql> // // here “//” Is the terminator
mysql> delimiter ;
mysql> show warnings;
mysql> call proc_name(1);
mysql> call proc_name(0);
Nine 、 The operation of modifying the column properties of a table
1、 To change the column a, from INTEGER Change it to TINYINT NOT NULL( Name the same ),
And change the column b, from CHAR(10) Change it to CHAR(20), And rename it , from b Change it to c:
mysql> ALTER TABLE t2 MODIFY a TINYINT NOT NULL, CHANGE b c CHAR(20);
2、 Add a new TIMESTAMP Column , be known as d:
mysql> ALTER TABLE t2 ADD d TIMESTAMP;
3、 In the column d Add an index to , And make the column a Primary key :
mysql> ALTER TABLE t2 ADD INDEX (d), ADD PRIMARY KEY (a);
4、 Delete column c:
mysql> ALTER TABLE t2 DROP COLUMN c;
5、 Add a new AUTO_INCREMENT Integer column , Name it c:
mysql> ALTER TABLE t2 ADD c INT UNSIGNED NOT NULL AUTO_INCREMENT,ADD INDEX ;
Be careful , We indexed c, because AUTO_INCREMENT Columns must be indexed , And in addition, we declare that c by NOT NULL,
Because indexed columns cannot be NULL
Ten 、 An instance of creating database and table and inserting data
drop database if exists school; // If there is SCHOOL Delete
create database school; // Build a library SCHOOL
use school; // Open the library SCHOOL
create table teacher // Create a table TEACHER
(
id int(3) auto_increment not null primary key,
name char(10) not null,
address varchar(50) default ‘ Shenzhen ’,
year date
); // End of watch building
// Here is the insert field
insert into teacher values(‘’,‘allen’,‘ Dalian No.1 Middle School ’,‘1976-10-10’);
insert into teacher values(‘’,‘jack’,‘ Dalian No.2 Middle School ’,‘1975-12-23’);
If you are in the mysql You can also type the above command at the prompt , But it's not convenient for debugging .
(1) You can write the above commands to a text file as is , Assuming that school.sql, Then copy it to c:\ Next , And in DOS Status into the directory \mysql\bin, Then type the following command :
mysql -uroot -p password < c:\school.sql
If it works , Empty a line without any indication ; If there is a mistake , There will be hints. .( The above command has been debugged , You just have to // You can use the ).
(2) Or go to the command line and use mysql> source c:\school.sql; Can also be school.sql The file is imported into the database .
MySQL Is a relational database (Relational Database Management System), This so-called " Relational type " It can be understood as " form " The concept of , A relational database consists of one or more tables , A table as shown in the figure :
Header (header): The name of each column ;
Column (row): A collection of data of the same data type ;
That's ok (col): Each line is used to describe someone / Specific information about things ;
value (value): Details of the line , Each value must be of the same data type as the column ;
key (key): The table is used to identify a specific person \ The method of things , The value of the key is unique in the current column .
MySQL Basic composition of script
Similar to regular scripting languages , MySQL Also has a set of pairs of characters 、 Rules for the use of words and special symbols , MySQL Through execution SQL Script to complete the operation of the database , The script consists of one or more MySQL sentence (SQL sentence + Extended statements ) form , When saving, the suffix of the script file is usually .sql. Under the console , MySQL The client can also execute a single sentence without saving it as .sql file .
identifier
Identifiers are used to name objects , Such as a database 、 surface 、 Column 、 Variable etc. , So that it can be referenced elsewhere in the script .MySQL Identifier naming rules are a little cumbersome , Here we use universal naming rules : Identifiers are made up of letters 、 Number or underscore (_) form , And the first character must be a letter or an underline .
Whether identifiers are case sensitive depends on the current operating system , Windows It's not sensitive under the circumstances , But for most linux\unix system , These identifiers are case sensitive .
MySQL Data types in
MySQL There are three types of data , They are numbers 、 date \ Time 、 character string , These three categories are further divided into many subtypes :
Numeric type
Integers : tinyint、smallint、mediumint、int、bigint
Floating point numbers : float、double、real、decimal
Date and time : date、time、datetime、timestamp、year
String type
character string : char、varchar
Text : tinytext、text、mediumtext、longtext
Binary system ( Can be used to store pictures 、 Music, etc ): tinyblob、blob、mediumblob、longblob
For details, see : 《MySQL data type 》 : http://www.cnblogs.com/zbseoag/archive/2013/03/19/2970004.html
Use MySQL database
Log in to MySQL
When MySQL When the service is already running , We can go through MySQL The self-contained client tools log in to MySQL In the database , First, open the command prompt , Enter the name of the following format :
mysql -h Host name -u user name -p
-h : The command to be used by the client to login MySQL Host name , Log in to the current machine. This parameter can be omitted ;
-u : The user name to log in to ;
-p : Tell the server that a password will be used to log in , If the username and password to log in are empty , You can ignore this option .
To log in to the MySQL Database, for example , Type... On the command line mysql -u root -p Press enter to confirm , If installed correctly and MySQL Running , You will get the following response :
Enter password:
If password exists , Enter password to log in , If it doesn't exist, just press enter to log in , Follow the installation method in this article , Default root The account has no password . You will see Welecome to the MySQL monitor… The hint of .
Then the command prompt will always be mysql> Add a blinking cursor to wait for the command input , Input exit or quit Log out .
Create a database
Use create database Statement can complete the creation of the database , The format of the create command is as follows :
create database Database name [ The other options ];
For example, we need to create a file called samp_db The database of , Execute the following command at the command line :
create database samp_db character set gbk;
In order to display Chinese in the command prompt , When created by character set gbk Specify the database character encoding as gbk. When created successfully, you will get Query OK, 1 row affected(0.02 sec) Response .
Be careful : MySQL The statement is semicolon (;) As the end of a sentence , If you don't add a semicolon at the end of a statement , The command prompt will use -> Prompt you to continue typing ( There are a few exceptions , But the semicolon can't be wrong );
Tips : have access to show databases; Command to see which databases have been created .
Select the database you want to operate on
To operate on a database , You must first select the database , Otherwise, the error will be prompted :
ERROR 1046(3D000): No database selected
The choice of two ways to use the database :
One : Specify when logging into the database , command : mysql -D The selected database name -h Host name -u user name -p
For example, when logging in, select the database you just created : mysql -D samp_db -u root -p
Two : Use after login use The statement specifies , command : use Database name ;
use Statements can be made without semicolons , perform use samp_db To select the database you just created , If you choose successfully, you will be prompted : Database changed
Create database tables
Use create table Statement to complete the creation of the table , create table A common form of :
create table The name of the table ( List of statements );
In order to create students Table as an example , The table will hold Student number (id)、 full name (name)、 Gender (sex)、 Age (age)、 contact number (tel) These content :
create table students
(
id int unsigned not null auto_increment primary key,
name char(8) not null,
sex char(4) not null,
age tinyint unsigned not null,
tel char(13) null default "-"
);
For some long statements, it may be easy to type incorrectly at the command prompt , Therefore, we can use any text editor to input the statement and save it as createtable.sql In the file of , Execute the script through file redirection at the command prompt .
Open Command Prompt , Input : mysql -D samp_db -u root -p < createtable.sql
( Tips : 1. If connecting to a remote host, please add -h Instructions ; 2. createtable.sql If the file is not in the current working directory, you need to specify the full path of the file .)
Sentence Explanation :
create table tablename(columns) The command to create a database table , The name of the column and the data type of the column will be completed in parentheses ;
It is stated in brackets that 5 Column content , id、name、sex、age、tel Name for each column , Followed by the data type description , Use commas between column descriptions (,) separate ;
With “id int unsigned not null auto_increment primary key” All right :
“id” Is the name of the column ;
“int” Specifies that the column is of type int( The value range is -8388608 To 8388607), In the back we use “unsigned” To embellish , Indicates that the type is unsigned , In this case, the value range of this column is 0 To 16777215;
“not null” Indicates that the value of the column cannot be empty , You have to fill in , If this property is not specified , It can be empty by default ;
“auto_increment” Use... In integer columns , Its function is to insert data if the column is NULL, MySQL A unique identifier value larger than the existing value will be automatically generated . There can only be one such value in each table, and the column must be an index column .
“primary key” Indicates that the column is the primary key of the table , The value of this column must be unique , MySQL The column will be automatically indexed .
Below char(8) Indicates that the stored character length is 8, tinyint The value range of is -127 To 128, default Property specifies the default value when the column value is empty .
For more data types, see 《MySQL data type 》 : http://www.cnblogs.com/zbseoag/archive/2013/03/19/2970004.html
Tips : 1. Use show tables; Command to see the name of the created table ; 2. Use describe Table name ; Command to view the details of the created table .
operation MySQL database
Insert data into table
insert Statements can be used to insert one or more rows of data into database tables , The general form used is as follows :
insert [into] Table name [( Name 1, Name 2, Name 3, …)] values ( value 1, value 2, value 3, …);
among [] The content in is optional , for example , To give samp_db In the database students Table inserts a record , Execute statement :
insert into students values(NULL, “ Wang Gang ”, “ male ”, 20, “13811371377”);
Press enter to confirm, if prompt Query Ok, 1 row affected (0.05 sec) Indicates that the data is inserted successfully . If the insertion fails, please check whether the database to be operated has been selected .
Sometimes we just need to insert some data , Or not in the order of columns , You can use this form to insert :
insert into students (name, sex, age) values(“ Sun Lihua ”, “ Woman ”, 21);
Query data in table
select Statements are often used to get data from the database according to certain query rules , Its basic usage is :
select Column name from The name of the table [ Query criteria ];
For example, to query students The names and ages of all the students in the table , Input statement select name, age from students; The results are as follows :
mysql> select name, age from students;
+--------+-----+
| name | age |
+--------+-----+
| Wang Gang | 20 |
| Sun Lihua | 21 |
| Wang Yongheng | 23 |
| Zheng Junjie | 19 |
| Chen Fang | 22 |
| Zhang weipeng | 21 |
+--------+-----+
6 rows in set (0.00 sec)
mysql>
You can also use wildcards * Query all the contents of the table , sentence : select * from students;
Query by specific conditions :
where Keywords are used to specify query conditions , The usage form is : select Column name from The name of the table where Conditions ;
Let's look at information about all genders , Enter the query statement : select * from students where sex=“ Woman ”;
where Clauses support more than “where Name = value ” This query form of name equals value , Operators for general comparison operations are supported , for example =、>、<、>=、<、!= And some extension operators is [not] null、in、like wait . You can also use or and and Make a combination query , I will learn more advanced query methods in the future , No more introduction here .
Example :
The age of inquiry is 21 Information about everyone over the age of : select * from students where age > 21;
The query name has “ king ” Everyone's information of the word : select * from students where name like “% king %”;
Inquire about id Less than 5 And older than 20 All information about : select * from students where id<5 and age>20;
Update the data in the table
update Statement can be used to modify the data in the table , The basic form of use is :
update The name of the table set Column name = The new value where Update conditions ;
Examples of use :
take id by 5 The phone number of is changed to the default "-": update students set tel=default where id=5;
Increase the age of all 1: update students set age=age+1;
Call your cell phone 13288097888 The name of is changed to “ Zhang weipeng ”, Change the age to 19: update students set name=“ Zhang weipeng ”, age=19 where tel=“13288097888”;
Delete data from table
delete Statement is used to delete data from a table , The basic usage is :
delete from The name of the table where Delete the condition ;
Examples of use :
Delete id by 2 The line of : delete from students where id=2;
Delete all ages less than 21 Year old data : delete from students where age<20;
Delete all data in the table : delete from students;
Modification of the table after creation
alter table Statement is used to modify the table after creation , The basic usage is as follows :
Add columns
Basic form : alter table Table name add Name Column data type [after Insertion position ];
Example :
Add columns at the end of the table address: alter table students add address char(60);
In a age Insert column after column birthday: alter table students add birthday date after age;
Modify the column
Basic form : alter table Table name change Column name List new names New data types ;
Example :
Will table tel The column was renamed telphone: alter table students change tel telphone char(13) default “-”;
take name Change the data type of the column to char(16): alter table students change name name char(16) not null;
Delete column
Basic form : alter table Table name drop Column name ;
Example :
Delete birthday Column : alter table students drop birthday;
rename table
Basic form : alter table Table name rename The new name of the table ;
Example :
rename students The table is workmates: alter table students rename workmates;
Delete the entire table
Basic form : drop table Table name ;
Example : Delete workmates surface : drop table workmates;
Delete the entire database
Basic form : drop database Database name ;
Example : Delete samp_db database : drop database samp_db;
appendix
modify root User password
According to the installation method in this article , root The user has no password by default , reset root There are many ways to use passwords , Here is just a more common way .
Use mysqladmin The way :
Open the command prompt interface , Carry out orders : mysqladmin -u root -p password New password
After execution, you will be prompted to input the old password to complete the password modification , When the old password is empty, just press enter to confirm .
Visual management tools MySQL Workbench
Although we can execute it at the command prompt by line by line input or by redirecting the file mysql sentence , But it's less efficient , Because there is no automatic syntax check before execution , The possibility of some errors caused by input errors will be greatly increased , Now try some Visualization MySQL Database management tools , MySQL Workbench Namely MySQL official by MySQL Provides a visual management tool , You can directly manage the contents of the database in a visual way , also MySQL Workbench Of SQL Script editor supports syntax highlighting and syntax checking during input , Of course , It's powerful , It's not just these two points .
MySQL Workbench The official introduction : http://www.mysql.com/products/workbench/
MySQL Workbench Download page : http://dev.mysql.com/downloads/tools/workbench/
The following is the linux Common instructions under :
Mysql The installation directory
Database directory
/var/lib/mysql/
The configuration file
/usr/share/mysql(mysql.server Commands and configuration files )
Relevant command
/usr/bin(mysqladmin mysqldump Wait for the order )
The startup script
/etc/init.d/mysql( Start script file mysql The catalog of )
System management
appendix :
Solve the problem that Chinese cannot be inserted into the database . I thought the code was set to UTF8, There will be no problem in dealing with Chinese , Then I went to play happily MySql, But something is wrong . Cannot insert Chinese !!!!】
This is normal insert data :
But in and out of Chinese , But it was wrong. .
When I can't think of my sister , I think about coding , So I checked the coding settings ,utf8!! According to the Internet, it is right
So I meditated , What's the problem , It's also reinstalled N Time , I want to screw up the computer , Those unreliable materials on the Internet have killed me .
By the way , Reinstall later MySql when , If there is an error that the service cannot be started in the last step , You can see C:\Documentsand Settings\AllUsers\Application Data Under this directory MySql Whether the package has been deleted , By default , This file path is hidden . Did not delete this file , It can't be reinstalled . No doubt. , I tried .
By MySql The problem of not being able to insert Chinese was tortured for two hours , It suddenly occurred to me that I had run into it before , It was solved later , There is a summary , So , I did it again according to the summary method , That's it .
Follow the method below Just modify a few codes
To test , All right
stay UI There is no garbled code in
SET character_set_client =gbk; // Set the customer service code
SET character_set_results =gbk // Set the returned code of the server-side result
SET character_set_connection =gbk // Set the code when the customer service end is connected with the service end
=====================================================================
a) Create a BookManagement( Book management ) The database of
create database bookmanagment;
b) Create a Book( The book ) Table for , Contains the following fields and records :
create table book(bookid int(2),name varchar(50),isbn varchar(20),authors varchar(100),category varchar(20),price double(10,2),publisher varchar(50),publishdate date,cover varchar(100),stock int(2));
mysql> insert into book values(1," Java object-oriented programming ","12345"," Sun Weiqin "," Computer ",78.00," electronics industry ","2007-02-01","12345.jpg",5);......................................... mysql> insert into book values(7,"JSP Programming book ","54379","LynnJean"," Computer ",102.00," The machinery industry ","2005-5-1","54379.jpg",7);
mysql> insert into book values(8,"SSH actual combat ","21346","GalvinKlein"," Computer ",156.00," The machinery industry ","2007-8-1","21346.jpg",8);
mysql> insert into book values(9,".NET and JAVA Reverie ","95635","BillGates"," Computer ",99.00," electronics industry ","2009-10-1","95635.jpg",11);
mysql> insert into book values(10," Square and circle ","76890"," Qian Xueqiang "," literature ",35.70," The machinery industry ","2009-3-1","76890.jpg",10);
mysql> insert into book values(11," Roman holiday ","23457","StenvenQing"," literature ",56.00," Tsinghua University ","2009-9-1","23457.jpg",21);
mysql> insert into book values(12,"MySQL Treasure ","96545","MySQLCorp"," Computer ",100.9," Tsinghua University ","2008-8-1","96545.jpg",1);
c) utilize Insert into Statement to insert the above record .
d) Query all the data in the table , In descending order of book number (order by)
select * from book order by bookid desc;
e) All publication dates in the query table are 2009 Book information for (where)
select * from book where year(publishdate)=”2009”;
f) List the information of all publishers in the table (distinct)
select distinct publisher from book;
g) The inquiry price is greater than 100 Yuan or the publishing house is “ Tsinghua University ” Book information of (or)
select * from book where price>100 or publisher=” Tsinghua University ”;
h) Query all book names with “java” Book information of (like)
select * from book where name like “%java%”;
i) Calculate the book category as “ Computer ” Number of books (group by)
select category,sum(stock) from book where category=” Computer ”group by category;
j) Calculate the number of books published by each publishing house (group by)
select publisher,sum(stock) from book group by publisher;
========================================================================
One Words explain (2 branch / individual ) 34 branch
Data data Database database RDBMS Relational database management system GRANT to grant authorization
REVOKE Cancellation of authority DENY Refused permission DECLARE Defining variables PROCEDURE stored procedure
Business Transaction trigger TRIGGER continue continue only unqiue
Primary key primary key Identity column identity Foreign keys foreign key Check check
constraint constraint
- Create a student table , Contains the following information , Student number , full name , Age , Gender , Home address , contact number
create table student
(
Student number int,
full name varchar(10),
Age int,
Gender varchar(4),
Home address varchar(50),
contact number varchar(11)
);
- Modify the structure of the student table , Add a column of information , Education
alter table student add column Education varchar(6);
- Modify the structure of the student table , Delete a column of information , Home address
alter table student drop column Home address ;// Note here drop Instead of delete
- Add the following information to the student table :
Student number Name, age, gender, contact number, education background
1A22 male 123456 Primary school
2B21 male 119 Middle school
3C23 male 110 high school
4D18 Woman 114 university
insert into student ( Student number , full name , Age , Gender , contact number , Education ) values(1,“A”,22,“ male ”,“123456”,“ Primary school ”);
insert into student ( Student number , full name , Age , Gender , contact number , Education ) values(1,“B”,21,“ male ”,“119”,“ Middle school ”);
insert into student ( Student number , full name , Age , Gender , contact number , Education ) values(1,“C”,23,“ male ”,“123456”,“ high school ”);
insert into student ( Student number , full name , Age , Gender , contact number , Education ) values(1,“D”,23,“ Woman ”,“114”,“ university ”);
- Modify the data of the student table , Place the phone number in 11 The academic qualifications of the beginning students are changed to “ junior college ”
update student set Education =“ junior college ” where contact number like “11%”;
- Delete the data of the student table , Name with C start , The gender is ‘ male ’ Of the records deleted
delete from student where full name like “C” and Gender =“ male ”;
- Query the data of the student table , All ages less than 22 Year old , Educational background “ junior college ” Of , The student's name and student number are shown
select full name , Student number from student where Age <22 and Education =“ junior college ”;
- Query the data of the student table , Look up all the information , Before listing 25% The record of
select top 25 percent * from student ; ???
select * from student limit 25%;???
There is something wrong with this one , stay sql 2000 It should be select top 25 percent * from student ;
9) Find out the names of all the students , Gender , In descending order of age
select full name , Gender , Age from student order by Age desc;
- Query all the average ages by sex
select avg( Age ) as Average age from student group by Gender ;
select avg( Age ) from student group by Gender ;
select avg( Age ) Average age from student group by Gender ;
3) Say the meaning of the following aggregate numbers :avg ,sum ,max ,min , count ,count(*)
AVG: averaging
SUM: Sum up
MAX: For maximum
MIN: For the minimum
COUNT(*): Returns the number of all rows
COUNT Returns the record value that meets the specified condition
边栏推荐
猜你喜欢

汇编_常用指令

SQL:锦标赛优胜者

Flyway management database

Question about Oracle: why can't the DBMS be linked according to the evening tutorial and output results

RMAN备份概念_关于RMAN增量备份(RMAN INCREMENTAL BACKUP)

【天线】【1】一些名词和简单概念的解释

RMAN备份概念_关于备份集(Backup Set)

【matlab】【数模】【1】linprog求解线性规划,标准型

安装mysql保姆级教程

Dell iDRAC Express版本的共享网口设置
随机推荐
【matlab】【数模】【1】linprog求解线性规划,标准型
2022-2028 global TSCM equipment industry research and trend analysis report
48-oidc OP configuration information endpoint
Direct application of 10 kinds of question type explosive text title sentence patterns
English语法_副词
SQL: people flow in the gymnasium (common solution for continuous day cases)
阿里云IOT
85. (leaflet house) leaflet military plotting - line arrow drawing
2022年5月29日16:05:09
SQL:市场分析 I
Summary of string inversion methods
10 个派上用场的 Flutter 小部件
RMAN备份概念_一致的和不一致的RMAN备份
配置RMAN备份的环境_配置高级的备份选项
Nacos二次开发
RMAN备份概念_关于RMAN备份的多个拷贝
认识了一位大佬!
AtCoder Beginner Contest 252
Open source EDA software yosys for integrated circuit design 1: tool installation
Codeforces Round #797 (Div. 3) A~E题解记录