Home>

First, connect to mysql

Format:mysql -h host address -u user name -p user password

1. Connect to mysql on this machine.

First open the dos window, then go to the directory mysql \ bin, and then type the command mysql -u root -p. After you press Enter, you are prompted to enter your password.Note that there can be spaces before or after the username,But there must be no spaces before the password,Otherwise, it will ask you to re-enter your password.

If you just installed mysql, the super user root has no password.So just press Enter to enter mysql. The prompt for mysql is:mysql>

2. Connect to mysql on the remote host. Assume that the IP address of the remote host is 110.110.110.110, the user name is root, and the password is abcd123. Then type the following command:

mysql -h110.110.110.110 -u root -p 123;(Note:there is no need to add spaces between u and root,Same for others)

3. Exit the mysql command:exit (Enter)

Second, change the password

Format:mysqladmin -u username -p old password password new password

1. Add a password ab12 to root.

First enter the directory mysql \ bin under dos, then type the following command

mysqladmin -u root -password ab12

Note:Because root has no password at the beginning,So the -p old password can be omitted.

2. Change the root password to djg345.

mysqladmin -u root -p ab12 password djg345

Third, add new users

Note:Unlike above,The following is the command in the mysql environment,So with a semicolon as the command terminator

Format:grant select on database. * To [email protected] identified by "password"

1. Add a user test1 with the password abc so that he can log in on any host.And have query, insert, modify, delete permissions on all databases.First connect to mysql as the root user, and then type the following command:

grant select, insert, update, delete on *. * to [[email protected]"%] test1 @"%[/email] "identified by" abc ";

But adding users is very dangerous.If i want someone to know the password of test1, then he can log in to your mysql database on any computer on the internet and do whatever he wants with your data.See 2.

2. Add a user test2 with a password of abc, so that he can only log in on localhost and query, insert, modify and delete the database mydb(That is, the host where the mysql database is located), so that even if the user knows the password of test2, he cannot directly access the database from the internet.It can only be accessed through a web page on the mysql host.

grant select, insert, update, delete on mydb. * to [[email protected]] [email protected] [/email] identified by "abc";

If you don't want test2 to have a password, you can type another command to remove the password.

grant select, insert, update, delete on mydb. * to [[email protected]] [email protected] [/email] identified by "";

Four:advanced database operations

4.1 Create Database

Note:you must connect to the mysql server before creating the database

Command:create database<database name>

Example 1:Create a database named xhkdb

mysql>create database xhkdb;

Example 2:Create a database and assign users

① create database database name;

②grant select, insert, update, delete, create, drop, alter on database name.* to database [email protected] identified by "password";

Execute 3 commands in turn to complete the database creation.Note:Chinese "password" and "database" are set by the user.

4.2 Displaying the database

Command:show databases (note:there is an s at the end)

mysql>show databases;

Note:In order to garble when it is no longer displayed,To modify the database default encoding.The following uses the GBK coded page as an example:

1. Modify the mysql configuration file:modify default-character-set=gbk in my.ini

2. Code runtime modification:

①Java code:jdbc:mysql://localhost:3306/test?useunicode=true&characterencoding=gbk

② 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 a valid character set name.Connection collation becomes the default collation of the character set.This function works similarly to the set names statement,But it can also set the value of mysql->charset, which affects the character set set by mysql_real_escape_string ().

4.3 Delete Database

Command:drop database<database name>

For example:delete the database named xhkdb

mysql>drop database xhkdb;

Example 1:Delete an existing database

mysql>drop database drop_database;

query ok, 0 rows affected (0.00 sec)

Example 2:Delete an uncertain database

mysql>drop database drop_database;

error 1008 (hy000):can "t drop database" drop_database ";database doesn" t exist

//An error occurred,The "drop_database" database cannot be dropped, it does not exist.

mysql>drop database if exists drop_database;

query ok, 0 rows affected, 1 warning (0.00 sec) //Generate a warning that this database does not exist

mysql>create database drop_database;

query ok, 1 row affected (0.00 sec)

mysql>drop database if exists drop_database;//if exists to determine whether the database exists,Does not exist or produces an error

query ok, 0 rows affected (0.00 sec)

4.4 Connecting to the database

Command:use<database name>

For example:if the xhkdb database exists,Try to access it:

mysql>use xhkdb;

Screen prompt:database changed

The use statement can tell mysql to use the db_name database as the default (current) database.Used for subsequent statements.This database remains the default database,Until the end of the paragraph,Or until a different use statement is issued:

mysql>use db1;

mysql>select count (*) from mytable;#selects from db1.mytable

mysql>use db2;

mysql>select count (*) from mytable;#selects from db2.mytable

Use the use statement to mark a specific current database,Does not prevent you from accessing tables in other databases.The following example can access the author table from the db1 database,And access the edit table from the db2 database:

mysql>use db1;

mysql>select author_name, editor_name from author, db2.editor

->Where author.editor_id=db2.editor.editor_id;

The use statement is set up,Used for compatibility with sybase.

Some netizens asked,How to exit after connecting.Actually, there is no need to exit.After using the database,Use show databases to query all databases,If i want to jump to another database,use

use other database name

That's it.

4.5 The currently selected database

Command:mysql>select database ();

The select command in mysql is similar to print or write in other programming languages. You can use it to display the results of a string, number, mathematical expression, and so on.How to use the special function of the select command in mysql?

1.Show mysql version

mysql>select version ();

+ ----------------------- +

| version () |

+ ----------------------- +

| 6.0.4-alpha-community |

+ ----------------------- +

1 row in set (0.02 sec)

2. Display the current time

mysql>select now ();

+ --------------------- +

| now () |

+ --------------------- +

| 2009-09-15 22:35:32 |

+ --------------------- +

1 row in set (0.04 sec)

3. Display the date

select 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)

Display string

mysql>select "welecome to my blog!";

+ ---------------------- +

| welecome to my blog! |

+ ---------------------- +

| welecome to my blog! |

+ ---------------------- +

1 row in set (0.00 sec)

5. When used as a calculator

select ((4 * 4)/10) + 25;

+ ---------------------- +

| ((4 * 4)/10) + 25 |

+ ---------------------- +

| 26.60 |

+ ---------------------- +

1 row in set (0.00 sec)

6. Concatenate strings

select 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 concatenate strings.In addition, we also used the previously learned as to give a pseudonym to the result column "concat (f_name," ", l_name)".

5.1 Create a data table

Command:create table<table name><field name 1><type 1>[, ..<field name n><type n>]);

For example, create a table named myclass,

Field name Number type Data width Is empty Whether the primary key Automatic increase Defaults
id int 4 no primary key auto_increment
name char 20 no
sex int 4 no 0
degree double 16 Yes

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));

5.3 Delete data table

Command:drop table<table name>

For example:delete the table named myclass

mysql>drop table myclass;

drop table is used to drop one or more tables.You must have drop permissions on each table. All table data and table definitions will be cancelled.So be careful with this statement!

Note:For a table with partitions,drop table will permanently undefine the table,Cancel each partition,And cancel all data stored in these partitions.Drop table also cancels the partition definition (.par) file associated with the dropped table.

For non-existing tables,Use if exists to prevent errors.When using if exists, for each table that does not exist,A note is generated.

Restrict and cascade can make partitioning easier.Currently, restrict and cascade do not work.

5.4 Table Insert Data

Command:insert into<table name>[(<field name 1>[, ..<field name n>])] values ​​(value 1) [, (value n)]

For example:insert two records into the table myclass, These two records indicate that the number 1 named tom has a score of 96.45, the number 2 named joan has a score of 82.99, and the number 3 named wang has a score of 96.5.

mysql>insert into myclass values ​​(1, "tom", 96.45), (2, "joan", 82.99), (2, "wang", 96.59);

Note:insert into can only insert one record into the table at a time.

5.5 Querying data in a table

1), query all rows

Command:select<field 1, field 2, ...>from<table name>where<expression>

For example:view all data in the table myclass

mysql>select * from myclass;

2) Query the first few rows of data

For example:view the first 2 rows of data in the table myclass

mysql>select * from myclass order by id limit 0,2;

select is generally used in conjunction with where to query more accurate and complex data.

5.6 Delete data from the table

Command:delete from table name where expression

For example:delete record number 1 in table myclass

mysql>delete from myclass where id=1;

The following is a comparison of the table before and after deleting data.

firstname lastname age
peter griffin 35
glenn quagmire 33

The following uses PHP code as an example to delete all records of lastname="griffin" 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 looks like this:

firstname lastname age
glenn quagmire 33

5.7 Modify the data in the table

Syntax:update table name set field=new value, ... where condition

mysql>update myclass set name="mary" where id=1;

Example 1:mysql update statement for a single table:

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 value.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 rows are updated in the specified order.The limit clause is used to give a limit,Limit the number of rows that can be updated.

5.8 Adding fields

Command:alter table table name add field type other;

For example:a field passtest is added to the table myclass, the type is int (4), the default value is 0

mysql>alter table myclass add passtest int (4) default "0"

Index

mysql>alter table table name add index index name (field name 1 [, field name 2…]);

Example:mysql>alter table employee add index emp_name (name);

Index of the primary key

mysql>alter table table name add primary key (field name);

Example:mysql>alter table employee add primary key (id);

Index with unique constraints

mysql>alter table table name add unique index name (field name);

Example:mysql>alter table employee add unique emp_name2 (cardnumber);

Delete an index

mysql>alter table table name drop index index name;

Example:mysql>alter table employee drop index emp_name;

Add field:

mysql>alter table table_name add field_name field_type;

Modify the original field name and type:

mysql>alter table table_name change old_field_name new_field_name field_type;

Delete field:

mysql alter table table_name drop field_name;

5.9 Modify the table name

Command:rename table original table name to new table name;

For example:in the table myclass name is changed 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, and create and insert permissions on the new table.

If you rename multiple tables,mysql encountered any errors,It will rename all the renamed tables,Return everything to its original state.

rename table was added in mysql 3.23.23.

6, backup database

The command is executed in the [url=file://\\ mysql \\ bin] \\ mysql \\ bin [/url] directory of dos

1. Export the entire database

The export file is stored in the mysql \ bin directory by default.

mysqldump -u username -p database name>exported file name

mysqldump -u user_name -p123456 database_name>outfile_name.sql

2. Export a table

mysqldump -u username -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 add a drop table before each create statement

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 the file back_aaa:

[[email protected] root] #cd/home/data/mysql

[[email protected] mysql] #mysqldump -u root -p --opt aaa>back_aaa

7.1 An example of database and table 1

drop database if exists school;//Delete if school exists
create database school;//Create a library school
use school;//open library school
create table teacher
(
  id int (3) auto_increment not null primary key,  name char (10) not null,  address varchar (50) default "Shenzhen",  year date
);//end the table
//The following is the inserted field
insert into teacher values ​​("," allen "," Dalian No.1 Middle School "," 1976-10-10 ′);
insert into teacher values ​​("," jack "," Dalian Second Middle School "," 1975-12-23 ′);

If you type the above command at the mysql prompt,But it is not convenient to debug.

1. You can write the above command as it is into a text file,Suppose it is school.sql, then copy it to c:\\, and enter the directory [url=file://\\ mysql \\ bin] \\ mysql \\ bin [/url] in dos state, and then type the following :

mysql -uroot -p password<c:\\ school.sql

If successful,Leave a blank line without any display;If there are errors,There will be a prompt.(The above command has been debugged,You just need to remove the comment of //to use).

2. Or use mysql>source c:\\ school.sql;after entering the command line. You can also import the school.sql file into the database.

7.2 An example of building a database and building a table 2

drop database if exists school;//Delete if school exists
create database school;//Create a library school
use school;//open library school
create table teacher
(
  id int (3) auto_increment not null primary key,  name char (10) not null,  address varchar (50) default "" Shenzhen "",  year date
);//end the table
//The following is the inserted field
insert into teacher values ​​("" "" "," "glchengang" "," "Shenzhen First Middle School" "," "1976-10-10" ");
insert into teacher values ​​("" "", "" jack "", "" Shenzhen First Middle School "", "" 1975-12-23 "");

Note:In the table

1. Set the id to a numeric field of length 3:int (3);and let it automatically add one for each record:auto_increment;it cannot be empty:not null;and make him the primary field primary key.

2.Set name to a character field with a length of 10

3. Set address to a character field of length 50.And the default is Shenzhen.

4. Set year to the date field.

  • Previous Analysis of SQL data manipulation statements
  • Next GIF image verification code in PHP