MySQL command Daquan

Source: Internet
Author: User
Tags mul mysql host mysql update

MySQL is a relational database management system, because of its small size, fast, low total cost of ownership, especially the open source of this feature, the general development of small and medium-sized web sites have chosen MySQL as a Web site database. Thanks to the performance of its community edition, PHP and Apache make a good development environment.

"Connect MySQL database"

MySQL command format: mysql-h host address-u user name-P user Password
1) Connect to the local MySQL first open the DOS window, then enter the directory Mysql\bin, and then type the command Mysql-u root-p, enter after the prompt you to lose the password.
Note that you can have a space before the user name, but there must be no space before the password, or let you re-enter the password.
If you have just installed MySQL, superuser root is no password, so the direct return to enter the MySQL, MySQL prompt is: mysql>
2) Connect to MySQL on the remote host assume that the IP of the remote host is:, the user name is root, and the password is abcd123. Type the following command: Mysql-h110.110.110.110-u root-p 123; (Note: You can use no space between the root and the other)
3) Exit MySQL command exit (enter)

"Modify User Password"

The Mysqladmin command is used to modify the user password.
mysqladmin command format: Mysqladmin-u user Name----old password password new password
1) Add a password to root ab12 First enter directory Mysql\bin under DOS, and then type the following command: Mysqladmin-u root-password ab12 Note: Because Root does not have a password at the beginning, the-P old secret Code one can be omitted.
2) Then change the root password to djg345 mysqladmin-u root-p ab12 password djg345

"Add new users and control their permissions"

Note: Unlike above, the following is because it is a command in the MySQL environment, so it is followed by a semicolon as the command terminator
The grant command is used to add new users and control their permissions.
Grant on command format: Grant select on database. * To User name @ login host identified by "password";
1) Add a user test1, password for ABC, so that he can log on any host, and all databases have query, insert, modify, delete permissions. First connect to MySQL with the root user, and then type the following command: Grant Select,insert,update,delete on * * to [[email protected] "%][email protected]"%[/email ] "identified by" ABC ";
But the added user is very dangerous, you want to like someone to know test1 password, then he can be on any computer on the Internet to log into your MySQL database and your data can do whatever you like, the solution is as follows.
2) Add a user test2 password for ABC, so that he can only log on on localhost, and can query, insert, modify, delete the database mydb (localhost refers to the local host, that is, the MySQL database is located in the host),     This allows the user to use a password that knows test2, and he cannot access the database directly from the Internet, but only through a Web page on the MySQL host. Grant Select,insert,update,delete on mydb.* to [[E-mail Protected]][email protected][/email] identified by "ABC";
If you do not want to test2 have a password, you can call another command to erase the password. Grant Select,insert,update,delete on mydb.* to [[E-mail Protected]][email protected][/email] identified by ""; "CREATE DATABASE"The Create command is used for creating the database.
Create command format: CREATE DATABASE < DB name >;
Note: Connect to the MySQL server before creating the database.
1) Set up a database named XHKDB: mysql> Create DB xhkdb;
2) Create a database and assign users:
    1. CREATE database name;
    2. GRANT select,insert,update,delete,create,drop,alter on database name. * To database name @localhost identified by ' password ';
    3. SET PASSWORD for ' database name ' @ ' localhost ' = old_password (' password ');
Execute 3 commands in turn to complete the database creation. "Show all Databases"The show Databases command is used to display all databases.
Show databases command format: show databases; (Note: There is a last s)
For example:mysql> show databases;
Note: To modify the default encoding of the database in order not to be garbled at the time of display. The following is an example of the GBK encoding page.
1) Modify the MySQL configuration file: My.ini inside Modify DEFAULT-CHARACTER-SET=GBK
2) Code Runtime Modification:
    • PHP Code: Header ("content-type:text/html;charset=gb2312");
    • C language code: int mysql_set_character_set (mysql * mysql, char * csname); This function is used to set the default character set for the current connection. The string csname specifies 1 valid character set names. Connection proofing becomes the default proofing for character sets. This function works similarly to the set names statement, but it also sets the value of mysql-> CharSet, which affects the character sets set by the Mysql_real_escape_string ().

"Delete Database"

The drop command is used to delete a database.
Drop command format: Drop databases < database name >;
For example, delete the database named XHKDB: mysql> drop DB xhkdb;
[Example 1] Delete a database that has been determined to exist: mysql> drop DB drop_database; Query OK, 0 rows Affected (0.00 sec)
[Example 2] Delete an indeterminate database: mysql> drop DB drop_database; ERROR 1008 (HY000): Can ' t drop database ' drop_database '; Database doesn ' t exist//error occurred, cannot delete ' drop_database ' databases, the database does not exist.
Mysql> drop database if exists drop_database; Query OK, 0 rows affected, 1 Warning (0.00 sec)//generates a warning stating that this database does not exist
mysql> CREATE DATABASE Drop_database;  Create a database Query OK, 1 row Affected (0.00 sec) mysql> drop database if exists drop_database; If exists determines whether the database exists, does not exist or generates an error Query OK, 0 rows Affected (0.00 sec) "Working with Databases"The use command allows us to work with the database.
Use command format: Use < database name >;
For example, if the XHKDB database exists, try to access it: mysql> use XHKDB; Screen tip: Database changed
1) The USE statement can advertise that MySQL uses the Db_name database as the default (current) database for subsequent statements.    The database remains as the default database until the end of the segment, or until the next different use statement appears: mysql> use DB1;   Mysql> SELECT COUNT (*) from mytable;    # selects from db1.mytable mysql> use DB2;   Mysql> SELECT COUNT (*) from mytable; # selects from db2.mytable
2) using the USE statement to mark a particular current database does not prevent you from accessing tables in other databases.     The following example accesses the author table from the DB1 database and accesses the editor table from the DB2 database: mysql> use DB1; Mysql> SELECT author_name,editor_name from Author,db2.editor, WHERE author.editor_id = Db2.editor.ed itor_id;
The USE statement is set up to be compatible with Sybase.
Some netizens asked, how to quit after the connection. In fact, you do not have to quit, use the database, using show databases can query all the database, if you want to jump to other databases, use the other database name. "currently selected (connected) database"The Select command represents the currently selected (connected) database.
Select command format:mysql> Select Database ();
The select command in MySQL is similar to print or write in other programming languages, and you can use it to display the results of a string, a number, a mathematical expression, and so on. How do I use the special features of the Select command in MySQL?
1) Show MySQL versionMysql> select version (); +-----------------------+  |  Version () | +-----------------------+  |  6.0.4-alpha-community | +-----------------------+ 1 row in Set (0.02 sec)
2) Show current timeMysql> Select Now (); +---------------------+  |  Now () | +---------------------+  |  2009-09-15 22:35:32 | +---------------------+ 1 row in Set (0.04 sec)
3) Display Month DaySELECT DayOfMonth (current_date); +--------------------------+  |  DayOfMonth (current_date) |                       +--------------------------+  |  15 |  +--------------------------+ 1 row in Set (0.01 sec) SELECT MONTH (current_date); +---------------------+  |  MONTH (current_date) |                   +---------------------+  |  9 |  +---------------------+ 1 row in Set (0.00 sec) SELECT Year (current_date); +--------------------+  |  Year (current_date) |               +--------------------+  |  2009 | +--------------------+ 1 row in Set (0.00 sec)
4) Display stringMysql> Select "Welecome to my blog!"; +----------------------+  |  Welecome to my blog! | +----------------------+  |  Welecome to my blog! | +----------------------+ 1 row in Set (0.00 sec)
5) When the calculator usesSelect ((4 * 4)/10) + 25; +----------------------+  |  ((4 * 4)/10) + 25 |                +----------------------+  |  26.60 | +----------------------+ 1 row in Set (0.00 sec)
6) Threaded stringSelect CONCAT (F_name, "", L_name) as name from Employee_data where title = ' Marketing Executive '; +---------------+  |  Name | +---------------+  |  Monica Sehgal | |  Hal Simlai | |  Joseph Irvine | +---------------+ 3 rows in Set (0.00 sec)
Note: the concat () function is used here to string strings together. In addition, we used the previously learned as to give the result column ' CONCAT (f_name, "", L_name) ' a pseudonym. "Create data table"The CREATE TABLE command is used for creating data tables.
CREATE TABLE command format: CREATE table < table name > (< Field name 1> < type 1> [,.. < Field name N> < type n>]);
For example, create a table named MyClass: is
Field name Number Type Data Widthempty whether the primary key automatically add Default Value
Id Int 4 Whether Primary key Auto_increment
Name Char 20 Whether
Sex Int 4 Whether 0
Degree Double 16 Is
Mysql> CREATE TABLE MyClass (> ID int (4) NOT null primary key auto_increment, > Name char (a) NOT NULL, > Sex int (4) NOT null default ' 0 ', > Degree double (16,2)); "Get data table structure"The desc command is used to get the data table structure.
DESC command format: DESC table name; Same Show columns from table name; The data table structure can also be obtained.
Examples are as follows: mysql> desc MyClass; Mysql> show columns from MyClass;
Using the MySQL database desc table name, we see the key column, there may be 4 kinds of values, namely ', ' PRI ', ' UNI ', ' MUL '.
    1. If the key is empty, the column value can be duplicated, indicating that the column has no index, or is a non-leading column of a non-unique composite index;
    2. If key is a PRI, then the column is part of the primary key;
    3. If key is uni, then the column is the first column (the leading column) of a unique value index and must not contain a null value (NULL);
    4. If key is Mul, then the value of the column can be repeated, which is a leading column of a non-unique index (the first column) or a component of a unique index but can contain null values.
If the definition of a column satisfies many of the above 4 cases, for example, if a column is both a PRI and a UNI, then the key value shown in the "DESC table name" is displayed as a priority for Pri->uni->mul. So at this point, the PRI is displayed.
A unique index column can be displayed as a PRI, and the column cannot contain null values, and the table does not have a primary key.
A unique index column can be displayed as Mul if multiple columns constitute a unique composite index, because although the multiple-column combination of indexes is unique, such as Id+name is unique, no single column can still have duplicate values, as long as Id+name is unique. "Delete data table"The drop TABLE command is used to delete a data table.
DROP TABLE command format: DROP table < table name >;
For example, delete the table named MyClass: mysql> drop table MyClass;
Drop table is used to delete one or more tables. You must have drop permissions for each table. All table data and table definitions are canceled, so use this statement with caution!
Note: For a partitioned table, the DROP table permanently cancels the tables definition, cancels the partitions, and cancels all the data stored in those partitions. DROP table also cancels the partition definition (. par) file that is associated with the canceled table.
For tables that do not exist, use the if exists to prevent errors from occurring. When using the if exists, a note (warning) is generated for each table that does not exist.
Restrict and cascade can make partitioning easier. Currently, restrict and cascade do not work. "inserting data into a table"The INSERT INTO command is used to insert data into the table.
INSERT INTO command format: INSERT into < table name > [(< Field name 1>[,.. < field name n >])] VALUES (value 1) [, (value N)];
For example: Insert two records into table MyClass, these two records indicate that: 1 is named Tom with a score of 96.45, 2 for the named Joan, and 82.99 for the number 3. mysql> INSERT INTO MyClass values (1, ' Tom ', 96.45), (2, ' Joan ', 82.99), (2, ' Wang ', 96.59);
Note: INSERT into only one record can be inserted into the table at a time. "Querying data in a table"The Select from command is used to query the data in the table.
1) query all rowsCommand format: Select < Field 1, Field 2, ...> from < table name > where < expression >;
For example, view all data in table MyClass: mysql> select * from MyClass;
2) Query the first few rows of dataFor example, view the first 2 rows of data in table MyClass: mysql> SELECT * FROM MyClass ORDER by ID limit 0, 2;
Select is typically used with where to query for more accurate and complex data. "Delete Record"The delete from command is used to delete data from a table.
Delete from command format: Delete from table name where expression
For example, delete the record numbered 1 in table MyClass: mysql> Delete from MyClass where id=1;
Please compare the table changes before and after deleting the data. Age
FirstName LastName
Peter Griffin 35
Glenn Quagmire 33
The following is an example of PHP code to delete all Lastname= ' Griffin ' records in the "Persons" table:
<?php    $con = mysql_connect ("localhost", "Peter", "abc123");    if (! $con) {die      (' Could not connect: '. Mysql_error ());    }    mysql_select_db ("my_db", $con);    mysql_query ("DELETE from Persons WHERE lastname= ' Griffin '"); Mysql_close ($con);?>

After this deletion, the table is like this:

FirstName LastName
Glenn Quagmire 33

"Modifying data in a table"

The update set command is used to modify the data in the table.
Update SET command format: Update table name SET field = new value,... where condition;
Examples are as follows: Mysql> update MyClass set name= ' Mary ' where id=1;
Example 1, single-table MySQL UPDATE statement: Update [low_priority] [IGNORE] tbl_name SET col_name1=expr1 [, col_name2=expr2 ...] [WHERE Where_definition] [ORDER by ...] [LIMIT Row_count];
Example 2, multi-table UPDATE statement: Update [low_priority] [IGNORE] table_references SET col_name1=expr1 [, col_name2=expr2 ...] [WHERE where_definition];
The update syntax can update the columns in the original table row with the new values. The SET clause indicates which columns to modify and which values to give. The WHERE clause specifies which rows should be updated. If there is no WHERE clause, all rows are updated. If an ORDER BY clause is specified, the row is updated in the order specified. The limit clause is used to limit the number of rows that can be updated, given a limit value. "add field for table"The alter ADD command is used to increase the table's fields.
Alter ADD command format: ALTER TABLE name add field type other;
For example, a field passtest is added to table MyClass, the type is int (4), and the default value is 0:mysql> ALTER TABLE MyClass add passtest int (4) default ' 0 ';
1) Gazzo PrimerMysql> ALTER TABLE name add index index name (field name 1[, field Name 2 ...]);
Example: mysql> ALTER TABLE employee ADD index emp_name (name);
2) Index of the plus primary keywordMysql> ALTER TABLE name add primary key (field name);
Example: mysql> ALTER TABLE employee ADD primary key (ID);
3) Index with unique restriction conditionsMysql> ALTER TABLE name add unique index name (field name);
Example: mysql> ALTER TABLE employee add unique emp_name2 (cardnumber);
4) Delete an indexmysql> ALTER TABLE name DROP INDEX name;
Example: Mysql>alter table employee DROP index emp_name;
5) Add Fieldmysql> ALTER TABLE table_name ADD field_name Field_type;
6) Modify the original field name and typemysql> ALTER TABLE table_name change old_field_name new_field_name field_type;
7) Delete fieldMySQL ALTER TABLE table_name DROP field_name; "Modify table name"The rename command is used to modify the table name.
Rename command format: Rename table name to the new table name;
For example, change the name in table MyClass to youclass:mysql> rename table MyClass to Youclass;
When you execute RENAME, you cannot have any locked tables or active transactions. You must also have ALTER and DROP permissions on the original table, as well as CREATE and INSERT permissions on the new table.
If MySQL encounters any errors in the multi-table renaming, it reverses all renamed tables, returning everything to its original state.
RENAME TABLE was added to MySQL 3.23.23. "Backing Up the database"

The mysqldump command is used to back up the database.
The mysqldump command executes under the DOS [Url=file://\\mysql\\bin]\\mysql\\bin[/url] directory.
1) Export the entire database (the export file is present in the Mysql\bin directory by default)

Mysqldump-u user name-p database name > exported file name

Mysqldump-u user_name-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 before each CREATE statement Add a drop table

4) Export with language parameters

mysqldump-uroot-p–default-character-set=latin1–set-charset=gbk–skip-opt database_name > Outfile_name.sql

For example, back up the AAA library to file back_aaa: [[email protected] root]# cd/home/data/mysql [[email protected] mysql]# mysqldump-u root-p--op T AAA > BACK_AAA

Related Article

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: 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.