2014-07-13 16:13:44
来 源
中存储网
MySQL
最近在Linux下需要使用到数据库MySQL,简单记录下学习笔记。我所使用的Linux系统是RedHat企业版本(Red Hat Enterprise Linux 5)一、查看MySql配置信息 1.查看版本相关信息 查看root用户没有密码的情况下: [Su

最近在Linux下需要使用到数据库MySQL,简单记录下学习笔记。

我所使用的Linux系统是RedHat企业版本(Red Hat Enterprise Linux 5)

一、查看MySql配置信息
  1.查看版本相关信息
  查看root用户没有密码的情况下:
  [Sunrier@localhost MySql]$ mysqladmin -u root version
  mysqladmin  Ver 8.41 Distrib 5.0.22, for redhat-linux-gnu on i686
  Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB
  This software comes with ABSOLUTELY NO WARRANTY. This is free software,
  and you are welcome to modify and redistribute it under the GPL license

  Server version          5.0.22
  Protocol version        10
Connection              Localhost via UNIX socket
  UNIX socket             /var/lib/mysql/mysql.sock
Uptime:                 20 min 9 sec

  Threads: 1  Questions: 28  Slow queries: 0  Opens: 0  Flush tables: 1  Open tables: 6  Queries per second avg:

  0.023

  [Sunrier@localhost MySql]$

  或者
  查看root用户带有密码的情况下:
  [Sunrier@localhost MySql]$ mysqladmin -u root -predhat version
  mysqladmin  Ver 8.41 Distrib 5.0.22, for redhat-linux-gnu on i686
  Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB
  This software comes with ABSOLUTELY NO WARRANTY. This is free software,
  and you are welcome to modify and redistribute it under the GPL license

  Server version          5.0.22
  Protocol version        10
Connection              Localhost via UNIX socket
  UNIX socket             /var/lib/mysql/mysql.sock
Uptime:                 20 min 9 sec

  Threads: 1  Questions: 28  Slow queries: 0  Opens: 0  Flush tables: 1  Open tables: 6  Queries per second avg:

  0.023

  [Sunrier@localhost MySql]$

  2.查看配置相关信息
  查看root用户没有密码的情况下:
  [Sunrier@localhost MySql]$mysqladmin variables
+---------------------------------+--------------------------------------------------------+
  | Variable_name                   | Value                                                  |
+---------------------------------+--------------------------------------------------------+
  | auto_increment_increment        | 1                                                      |
  | auto_increment_offset           | 1                                                      |
|..........................................................................................|
|..........................................................................................|
|..........................................................................................|                   |
  | version_compile_os              | redhat-linux-gnu                                       |
  | wait_timeout                    | 28800                                                  |
+---------------------------------+--------------------------------------------------------+
  [Sunrier@localhost MySql]$

  或者
  查看root用户带有密码的情况下:
  [Sunrier@localhost MySql]$ mysqladmin -u root -predhat variables
+---------------------------------+--------------------------------------------------------+
  | Variable_name                   | Value                                                  |
+---------------------------------+--------------------------------------------------------+
  | auto_increment_increment        | 1                                                      |
  | auto_increment_offset           | 1                                                      |
|..........................................................................................|
|..........................................................................................|
|..........................................................................................|                   |
  | version_compile_os              | redhat-linux-gnu                                       |
  | wait_timeout                    | 28800                                                  |
+---------------------------------+--------------------------------------------------------+
  [Sunrier@localhost MySql]$

   二、连接MYSQL。

  格式: mysql  -h主机地址  -u用户名  -p用户密码

  1.连接到本机上的MYSQL

    [Sunrier@localhost MySql]$ mysql

    Welcome to the MySQL monitor.  Commands end with ; or g.
    Your MySQL connection id is 6 to server version: 5.0.22

    Type 'help;' or 'h' for help. Type 'c' to clear the buffer.

     mysql>

     由于是刚安装的MYSQL,超级用户root是没有密码的,故直接回车即可进入到MYSQL中。

      如果root用户设置了密码,则输入mysql -u root -p回车后提示你输密码.注意用户名前可以有空格也可以没有空格,密码前没有空格,-p后面紧跟着密码,密码不要输入错误,否则让你重新输入密码.

      [Sunrier@localhost MySql]$ mysql -u root -p
      Enter password:
      Welcome to the MySQL monitor.  Commands end with ; or g.
      Your MySQL connection id is 5 to server version: 5.0.22

      Type 'help;' or 'h' for help. Type 'c' to clear the buffer.

       mysql>

     或者

      mysql -uroot -predhat
      Welcome to the MySQL monitor.  Commands end with ; or g.
      Your MySQL connection id is 36 to server version: 5.0.22

      Type 'help;' or 'h' for help. Type 'c' to clear the buffer.

       mysql>

    2、连接到远程主机上的MYSQL。假设远程主机的IP为:192.168.2.2,用户名为root,密码为Sunrier。则键入以下命令:

        [Sunrier@localhost MySql]$ mysql -h 192.168.2.2  -u root  -pSunrier;(注:u与root之间可以不用加空格,而-p后面需紧跟着密码,不能有空格,否则会提示你重新输入密码)

     3、退出MYSQL命令: exit (回车)

          mysql> exit
          Bye
[Sunrier@localhost MySql]$ 

三、修改密码。

格式:mysqladmin -u用户名 -p旧密码 password 新密码

   1.给root加个密码Sunrier。然后键入以下命令

   [Sunrier@localhost MySql]$ mysqladmin -u root  password Sunrier

   [Sunrier@localhost MySql]$

  或者 

 [Sunrier@localhost MySql]$ mysql -u root
  Welcome to the MySQL monitor.  Commands end with ; or g.
  Your MySQL connection id is 5 to server version: 5.0.22

  Type 'help;' or 'h' for help. Type 'c' to clear the buffer.

  mysql> set password=password('Sunrier‘);

  Query OK, 0 rows affected (0.01 sec)

  mysql> exit
  Bye
 [Sunrier@localhost MySql]$

2.将root用户以前的密码Sunrier改为linux。
[Sunrier@localhost MySql]$ mysqladmin -u root -pSunrier password linux
[Sunrier@localhost MySql]$

或者

  [Sunrier@localhost MySql]$ mysql -u root -p
  Enter password:
  Welcome to the MySQL monitor.  Commands end with ; or g.
  Your MySQL connection id is 5 to server version: 5.0.22

  Type 'help;' or 'h' for help. Type 'c' to clear the buffer.

  mysql> set password=password('linux');

  Query OK, 0 rows affected (0.01 sec)

  mysql> exit
  Bye
 [Sunrier@localhost MySql]$

四、添加用户
格式:grant (all?,select?,insert?,update?,delete?) on 数据库.* to 用户名@登录主机 identified by "密码"
1.增加一个用户sunrier密码为redhat,让他可以在任何主机上登陆,并对所有数据库有查询、插入、修改、删除的权限.首先用root用户连入MYSQL,然后键入以下命令:
mysql>grant select,insert,update,delete on *.* to sunrier@"%" identified by "redhat";
Query OK, 0 rows affected (0.00 sec)

mysql>
 这样增加的用户是十分危险的,你想如某个人知道sunrier的密码,那么他就可以在internet上的任何一台电脑上登陆你的mysql数据库并对你的数据可以为所欲为了,解决办法见2。

2.增加一个用户sunrier密码为redhat,让他只可以在localhost上登录,并可以对所有的数据库进行所有的操作(localhost指本地主机,即MYSQL数据库所在的那台主机)
这样用户即使用知道sunrier的密码,他也无法从internet上直接访问数据库,只能通过MYSQL主机上的web页来访问了
mysql>grant all on *.*  to sunrier@localhost identified by "redhat";
Query OK, 0 rows affected (0.00 sec)

mysql>

如果你不想sunrier有密码,可以再打一个命令将密码消掉。
mysql>grant all on *.*  to sunrier@localhost identified by "";
Query OK, 0 rows affected (0.00 sec)

mysql>

3.增加一个用户sunrier密码为redhat,让他只可以在localhost上登陆,并可以对数据库demo进行查询、插入、修改、删除的操作(localhost指本地主机,即MYSQL数据库所在的那台主机)
mysql>grant select,insert,update,delete on demo.* to sunrier@localhost identified by "redhat";
Query OK, 0 rows affected (0.00 sec)

mysql>

五、操作命令
1.显示当前数据库服务器中所有的数据库
mysql> show databases;
注意:mysql库里面有MYSQL的系统信息,我们改密码和新增用户,实际上就是用这个库进行操作。

例:
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| test               |
+--------------------+
4 rows in set (0.01 sec)

mysql>


2.建立数据库
mysql> create database 数据库名;


例:
mysql>grant all on *.*  to sunrier@localhost identified by "redhat";
Query OK, 0 rows affected (0.00 sec)

mysql> exit
Bye
[Sunrier@localhost MySql]$ mysql -u sunrier -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or g.
Your MySQL connection id is 5 to server version: 5.0.22

Type 'help;' or 'h' for help. Type 'c' to clear the buffer.

mysql> create database demo;
Query OK, 1 rows affected (0.01 sec)
mysql> use demo;
mysql>

3.显示当前使用的数据库
mysql> select database();

4.显示当前数据库中登陆的用户
mysql> select user();

5.显示当前数据库中有哪些数据表
mysql> use 数据库名;
mysql> show tables;

6.显示当前数据库中某个数据表的结构
mysql> describe 表名;

7.删除某个数据库:
mysql> drop database 数据库名;

8.建立数据表
mysql> use 数据库名;
mysql> create table 表名 (字段名 integer,字段名 varchar(30), 字段名 char(1));

例:
mysql> use demo;
Database changed
mysql> create table student(
mysql> studno integer auto_increment not null primary key,
mysql> fname varchar(30),
mysql> age integer
mysql> );
Query OK, 0 rows affected (0.04 sec)
mysql>

显示表结构:
mysql> describe student;
+---------+-------------+------+-----+---------+----------------+
| Field   | Type        | Null | Key | Default | Extra          |
+---------+-------------+------+-----+---------+----------------+
| studno  | int(11)     | NO   | PRI | NULL    | auto_increment |
| fname   | varchar(30) | YES  |     | NULL    |                |
| age     | int(11)     | YES  |     | NULL    |                |
+---------+-------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)

mysql>

9.向某个表中插入记录
mysql> insert into 表名 values (1,"xxx",18);

例:
mysql> insert into student values ("Sunrier",22);
Query OK, 1 rows affected (0.00 sec)
mysql> insert into student values ("Tom",23);
Query OK, 1 rows affected (0.00 sec)
mysql> insert into student values ("Jerry",21);
Query OK, 1 rows affected (0.00 sec)
mysql>

指定插入表的数据
mysql> insert into student(fname) values ("God");
Query OK, 1 rows affected (0.00 sec)
mysql>

10.显示某个表中的记录
mysql> select * from 表名;

例:
mysql> select * from student;
+---------+---------+------+
| studno  | fname   | age  |
+---------+---------+------+
|       1 | Sunrier |   22 |
|       2 | Tom     |   23 |
|       3 | Jerry   |   21 |
+---------+---------+------+
3 rows in set (0.00 sec)

mysql>

指定列的别名查询
mysql> select fname as '姓名' from student;
+---------+
| 姓名  |
+---------+
| Sunrier |
| Tom     |
| Jerry   |
+---------+
3 rows in set (0.00 sec)

mysql>

指定表的别名查询
mysql> select s1.studno,s1.fname,s1.age from student as s1;
+--------+---------+------+
| studno | fname   | age  |
+--------+---------+------+
|      1 | Sunrier |   22 |
|      2 | Tom     |   23 |
|      3 | Jerry   |   21 | 
+--------+---------+------+
3 rows in set (0.00 sec)

mysql>

添加说明列:
mysql> select fname ,"age is:",age from student;
+---------+---------+------+
| fname   | age is: | age  |
+---------+---------+------+
| Sunrier | age is: |   22 |
| Tom     | age is: |   23 |
| Jerry   | age is: |   21 |
+-------+---------+------+
3 rows in set (0.00 sec)

mysql>

查询年龄不重复的
mysql> select distinct age from student;
+------+
| age  |
+------+
|   22 |
|   23 |
|   21 | 
+------+
3 rows in set (0.00 sec)

mysql>


查询总记录数
mysql> select count(*) from student;
+----------+
| count(*) |
+----------+
|        3 |
+----------+
1 row in set (0.00 sec)


mysql>

 where子句使用的条件有:
比较运算符: > , < , >= , <= , <> , =
逻辑运算符: and , or ,  not
范围运算符: between and
列表运算符: in , not in
字符匹配:   like , not like
未知值: is null , is not null
字符串匹配查询: %表示通配符,代表任意多个字符;而_表示单个字符

11.更新表中数据
mysql-> update 表名 set 字段名1='x',字段名2='y' where 字段名3='z';

例:
mysql> update student set age=23 where fname='Jerry';
Query OK, 1 rows affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select * from student;
+---------+---------+------+
| stduno  | fname   | age  |
+---------+---------+------+
|       1 | Sunrier |   22 |
|       2 | Tom     |   23 |
|       3 | Jerry   |   23 |
+---------+---------+------+
3 rows in set (0.00 sec)

mysql>

12.用.sql文件导入数据库中的表结构
mysql> use 数据库名;
mysql> source .sql文件路径;

注:在.sql文件中注释符号用"-- "(--后面有一个空格)
例:
student.sql
create table student(
studno integer auto_increment not null primary key,
fname varchar(30),
age integer
);
--insert into student values ('',"Sunrier",22);
--insert into student values ('',"Tom",23);
--insert into student values ('',"Jerry",21);

mysql> use demo;
mysql> source /mnt/hgfs/Sunrier/MySql/student.sql;
Query OK, 0 rows affected (0.04 sec)

mysql>

13.用文本方式将数据装入一个数据表中:
mysql> load data local infile "文本路径" into table 表名;

例:
student.txt
1 Sunrier 22
2 Tom 23 
3 Jerry  23 
列之间使用TAB键分割(只能一个TAB键),null值用N来代替(注:N为大写字母),数据和表结构对应

mysql> load data local infile "/mnt/hgfs/Sunrier/MySql/student.txt" into table student;
Query OK, 0 rows affected, 5 warnings (0.00 sec)
Records: 3  Deleted: 0  Skipped: 3  Warnings: 5

mysql> select * from student;
+--------+---------+------+
| studno | fname   | age  |
+--------+---------+------+
|      1 | Sunrier |    0 |
|      2 | Tom     |    0 |
|      3 | Jerry   |    0 |
+--------+---------+------+
3 rows in set (0.00 sec)

mysql>

把数据库中student表里的数据导出到txt文件中
mysql> select * from student into outfile "/mnt/hgfs/Sunrier/MySql/student_out.txt" lines terminated by "rn";
其中lines terminated by "rn" 表示每一行(即每一条记录)用rn分隔,rn是window系统的换行符.导出的student_out.txt与student.txt的内容完全一样.

注意:
字段之间的分隔和记录(行)之间的分隔默认是t(即Tab)和n,但可以改变
如:
fields terminated by  ',' --字段用,进行分隔
lines terminated by  ';' --记录用; 进行分隔

如导入txt文件时,字段之间用的,分隔
load data local infile "路径" into table table_name fields terminated by ',' lines terminated by 'rn';
如:
mysql> load data local infile "/mnt/hgfs/Sunrier/MySql/student.txt" into table student fields terminated by ',' ;
 

例:
mysql> select * from student into outfile "/mnt/hgfs/Sunrier/MySql/student_out.txt";
等价于
mysql> select * from student into outfile '/mnt/hgfs/Sunrier/MySql/student_out.txt';

后面的双引号和单引号都可以。

直接导出的方式:
[Sunrier@localhost MySql]$ mysql -uSunrier -predhat -e "use test;select * from student into outfile '/mnt/hgfs/Sunrier/MySql/student_out.txt';"

[Sunrier@localhost MySql]$ mysql -uSunrier -predhat -e "use test;select * from student into outfile '/mnt/hgfs/Sunrier/MySql/student_out.txt' fields terminated by '|' lines terminated by '|rn' ;"

导出student_out.txt的内容为:
1|Jack|67|
2|Tim|22|
3|Sunrier|23|
4|Helen|26|
5|Tony|29|
6|Cherry|30|
7|Nicky|22|
8|Jerry|21|
9|Marry|23|

使用Linux下Shell脚本的方法: 

//exportRecords.sh

#!/bin/sh
#FileName:exportRecords.sh
#Function:Linux下使用Shell脚本导出表中的数据
#Version:V0.1
#Author:Sunrier
#Date:2012-07-30
mysql -uSunrier -predhat <<EOF
use test;
select concat(studno,"|", fname ,"|",age,"|") from student into outfile '/mnt/hgfs/Sunrier/MySql/student_out.txt';
EOF

14.将表中记录清空
mysql> delete from 表名;

例:
mysql> delete from student;
Query OK, 3 rows affected (0.00 sec)

mysql> select * from student;
Empty set (0.00 sec)

mysql>


15.删除数据库中的某个表
mysql> drop table 表名;


16.命令行修改root密码:
mysql> update mysql.user set password=password('新密码') where user='root';
mysql> flush privileges;
mysql>
注意用此种方法修改密码时别忘了 password=password('新密码') 如果直接用 password='新密码',下次登录时会出现问题以至于登录不进去,因为此密码没用经过password()函数处理,这样写入到user表中的密码系统不能识别就会显示用户名和密码错误的信息。如果在修改密码的过程中出现问题以至于没有一个用户可以进入mysql则可以用以下的方法重新修改用户名和密码:bin>mysqld --skip-grant-tables;然后再在 另外一个bin>mysql 便可直接进入mysql ,进入后便修改相关数据。

flush privileges:让MySql服务器重载它的权限表

17.删除用户Sunrier (注:demo表示某个数据库)
mysql> revoke all on demo.* from Sunrier@localhost;
mysql> use mysql;
mysql> delete from user where user='Sunrier';
mysql> flush privileges;

18.显示当前状态
mysql> show status;
+-----------------------------------+----------+
| Variable_name                     | Value    |
+-----------------------------------+----------+
| Aborted_clients                   | 0        |
| Aborted_connects                  | 1        |
| Binlog_cache_disk_use             | 0        |
| Binlog_cache_use                  | 0        |
| Bytes_received                    | 489      |
| Bytes_sent                        | 16206    |
| Com_admin_commands                | 0        |
| Com_alter_db                      | 0        |
| Com_alter_table                   | 0        |
| Com_analyze                       | 0        |
| Com_backup_table                  | 0        |
| Com_begin                         | 0        |
................................................
................................................
................................................
| Table_locks_waited                | 0        |
| Tc_log_max_pages_used             | 0        |
| Tc_log_page_size                  | 0        |
| Tc_log_page_waits                 | 0        |
| Threads_cached                    | 0        |
| Threads_connected                 | 1        |
| Threads_created                   | 2        |
| Threads_running                   | 1        |
| Uptime                            | 599      |
+-----------------------------------+----------+
245 rows in set (0.00 sec)

mysql>


19.显示有哪些线程在运行
mysql> show processlist;
+----+---------+-----------+------+---------+------+-------+------------------+
| Id | User    | Host      | db   | Command | Time | State | Info             |
+----+---------+-----------+------+---------+------+-------+------------------+
|  2 | Sunrier | localhost | test | Query   |    0 | NULL  | show processlist |
+----+---------+-----------+------+---------+------+-------+------------------+
1 row in set (0.00 sec)


mysql> show full processlist;
+----+---------+-----------+------+---------+------+-------+-----------------------+
| Id | User    | Host      | db   | Command | Time | State | Info                  |
+----+---------+-----------+------+---------+------+-------+-----------------------+
|  2 | Sunrier | localhost | test | Query   |    0 | NULL  | show full processlist |
+----+---------+-----------+------+---------+------+-------+-----------------------+
1 row in set (0.00 sec)

mysql>

注:show processlist只列出前100条;如果想全部列出请使用show full processlist


或者
[root@localhost ~]# mysqladmin -u root -predhat processlist
+----+------+-----------+----+---------+------+-------+------------------+
| Id | User | Host      | db | Command | Time | State | Info             |
+----+------+-----------+----+---------+------+-------+------------------+
| 11 | root | localhost |    | Query   | 0    |       | show processlist |
+----+------+-----------+----+---------+------+-------+------------------+
[root@localhost ~]#


注:如果是root帐号,你能看到所有用户当前连接的全部线程;如果是其它普通帐号,只能看到自己发起的线程占用的连接

六、举例实践
1.建库和建表以及插入数据的实例
drop database if exists school; --如果存在school则删除
create database school;  --建立库school

use school; --打开库school

create table teacher --建立表teacher
(
  id int(3) auto_increment not null primary key,
  name char(20) not null,
  address varchar(80) default '上海',
  year date
); --建表结束

--以下为插入数据字段
insert into teacher values('','Tom','上海徐汇中学','1990-08-06');
insert into teacher values('','Sunrier','田林中学','1989-06-27');

1).把上面文件内容放到school.sql里
[Sunrier@localhost MySql]$ mysql -uroot -predhat
Welcome to the MySQL monitor.  Commands end with ; or g.
Your MySQL connection id is 42 to server version: 5.0.22

Type 'help;' or 'h' for help. Type 'c' to clear the buffer.

mysql> source /mnt/hgfs/Sunrier/MySql/school.sql;
Query OK, 0 rows affected, 1 warning (0.00 sec)

Query OK, 1 row affected (0.00 sec)

Database changed
Query OK, 0 rows affected (0.00 sec)

Query OK, 1 row affected, 1 warning (0.00 sec)

Query OK, 1 row affected, 1 warning (0.00 sec)

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| school             |
| test               |
+--------------------+
4 rows in set (0.00 sec)

mysql> use school;
Database changed
mysql> select * from teacher;
+----+---------+--------------+------------+
| id | name    | address      | year       |
+----+---------+--------------+------------+
|  1 | Tom     | 上海徐汇中学 | 1990-08-06 |
|  2 | Sunrier | 田林中学     | 1989-06-27 |
+----+---------+--------------+------------+
2 rows in set (0.00 sec)

mysql>

六、备份数据库
1.导出整个数据库
  mysqldump -u 用户名 -p密码 数据库名 > 导出的文件名.sql
 导出的文件默认位置在当前目录下
 例子:
 [Sunrier@localhost MySql]$ mysqldump -u root -predhat school > Database_school_backup.sql
 [Sunrier@localhost MySql]$

使用shell脚本的方法备份数据库
//autobackup.sh

#!/bin/sh
#FileName:autobackup.sh
#Function:Shell脚本自动备份数据库
#Version:V0.1
#Author:Sunrier
#Date:2012-08-23
CURRPATH=$PWD
PROJPATH="/home/Sunrier/proj"
BAKPATH="/home/Sunrier/proj/bak"
MYSQLBINPATH="/usr/bin"
USER="root"
#USER="Sunrier"
PASSWORD="redhat"
DATABASENAME="school"
BakTime=`date +%Y%m%d`
BakName=$DATABASEName$BakTime
#mkdir $PROJPATH >/dev/null 2>&1
#mkdir $BAKPATH >/dev/null 2>&1
#假设目录路径都存在
MYSQLBINPATH/mysqldump -u $USER -p$PASSWORD $DATABASENAME | gzip > $BAKPATH/$BakName.gz
cd $CURRPATH
例:
-- MySQL dump 10.10
--
-- Host: localhost    Database: test
-- ------------------------------------------------------
-- Server version       5.0.22
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `teacher`
--
DROP TABLE IF EXISTS `teacher`;
CREATE TABLE `teacher` (
  `id` int(3) NOT NULL auto_increment,
  `name` char(20) NOT NULL,
  `address` varchar(30) default '上海',
  `year` date default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `teacher`
--
/*!40000 ALTER TABLE `teacher` DISABLE KEYS */;
LOCK TABLES `teacher` WRITE;
INSERT INTO `teacher` VALUES (1,'Tom','上海徐汇中学','1990-08-06'),(2,'Sunrier','田林中学','1989-06-27');
UNLOCK TABLES;
/*!40000 ALTER TABLE `teacher` ENABLE KEYS */;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

还原一个数据库
[Sunrier@localhost MySql]$ mysql -uroot -predhat school < /mnt/hgfs/Sunrier/MySql/Database_school_backup.sql
[Sunrier@localhost MySql]$

2.导出一个表
  mysqldump -u 用户名 -p密码 数据库名 表名> 导出的文件名.sql
 导出的文件默认位置在当前目录下
 例子:
 [Sunrier@localhost MySql]$ mysqldump -u root -predhat school teacher > Table_teacher_backup.sql
 [Sunrier@localhost MySql]$

还原一个数据库里面的表
[Sunrier@localhost MySql]$ mysql -uroot -predhat school < /mnt/hgfs/Sunrier/MySql/Table_teacher_backup.sql
[Sunrier@localhost MySql]$

3.导出一个数据库结构
  mysqldump -u 用户名 -p密码 -d --add-drop-table 数据库名 > 导出的文件名.sql
  -d 没有数据 --add-drop-table 在每个create语句之前增加一个drop table
  [Sunrier@localhost MySql]$ mysqldump -u root -predhat -d --add-drop-table school > Describe_school.sql
  [Sunrier@localhost MySql]$

4.带语言参数导出(显示中文,防止乱码)
  mysqldump -uroot -p --default-character-set=latin1 --set-charset=gbk --skip-opt database_name > 导出的文件名.sql
  [Sunrier@localhost MySql]$ mysqldump -uroot -predhat --default-character-set=latin1 --skip-opt school > Language_school.sql
  [Sunrier@localhost MySql]$

  --default-characte-set 以前数据库的字符集,这个一般情况下都是latin1的,
  --set-charset 导出的数据的字符集,这个可以设置为gbk,utf8,或者big5

 七、数据库字符集编码格式

查看数据库字符集设置
[Sunrier@localhost MySql]$ mysql -uroot -predhat
Welcome to the MySQL monitor.  Commands end with ; or g.
Your MySQL connection id is 23 to server version: 5.0.22

Type 'help;' or 'h' for help. Type 'c' to clear the buffer.

mysql> show variables like 'character_set_%';
+--------------------------+----------------------------+
| Variable_name            | Value                      |
+--------------------------+----------------------------+
| character_set_client     | latin1                     |
| character_set_connection | latin1                     |
| character_set_database   | utf8                       |
| character_set_filesystem | binary                     |
| character_set_results    | latin1                     |
| character_set_server     | utf8                       |
| character_set_system     | utf8                       |
| character_sets_dir       | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
8 rows in set (0.00 sec)

mysql>

设置MySQL编码为utf8

修改/etc/my.cnf配置文件
[mysqld]
#default strogage engine for the MyISAM.
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
# Default to using old password format for compatibility with mysql 3.x
# clients (those using the mysqlclient10 compatibility package).
old_passwords=1

init_connect='SET NAMES utf8'

#set default character ---Sunrier
default-character-set=utf8
[mysql.server]
user=mysql
basedir=/var/lib

#Sunrier
default-character-set=utf8

[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid

#Sunrier
default-character-set=utf8

#Sunrier
[client]
default-character-set=utf8

 保存后重启MySQL

mysql> show variables like 'character_set_%';
+--------------------------+----------------------------+
| Variable_name            | Value                      |
+--------------------------+----------------------------+
| character_set_client     | utf8                     |
| character_set_connection | utf8                     |
| character_set_database   | utf8                       |
| character_set_filesystem | utf8                     |
| character_set_results    | utf8                    |
| character_set_server     | utf8                       |
| character_set_system     | utf8                       |
| character_sets_dir       | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
8 rows in set (0.00 sec)

mysql>

注:下次退出重新查看其中character_set_filesystem 还为| character_set_filesystem | binary                     | 

八、设置MySQL默认引擎为InnoDB

MySQL默认的数据库引擎是MyISAM,不支持事务和外键,也可使用支持事务和外键的InnoDB。
查看当前数据库的所支持的数据库引擎以及默认数据库引擎:
[Sunrier@localhost MySql]$ mysql -uroot -predhat
Welcome to the MySQL monitor.  Commands end with ; or g.
Your MySQL connection id is 19 to server version: 5.0.22

Type 'help;' or 'h' for help. Type 'c' to clear the buffer.

mysql> show engines;
+------------+---------+----------------------------------------------------------------+
| Engine     | Support | Comment                                                        |
+------------+---------+----------------------------------------------------------------+
| MyISAM     | DEFAULT | Default engine as of MySQL 3.23 with great performance         |
| MEMORY     | YES     | Hash based, stored in memory, useful for temporary tables      |
| InnoDB     | DISABLED| Supports transactions, row-level locking, and foreign keys     |
| BerkeleyDB | YES     | Supports transactions and page-level locking                   |
| BLACKHOLE  | NO      | /dev/null storage engine (anything you write to it disappears) |
| EXAMPLE    | NO      | Example storage engine                                         |
| ARCHIVE    | NO      | Archive storage engine                                         |
| CSV        | NO      | CSV storage engine                                             |
| ndbcluster | NO      | Clustered, fault-tolerant, memory-based tables                 |
| FEDERATED  | NO      | Federated MySQL storage engine                                 |
| MRG_MYISAM | YES     | Collection of identical MyISAM tables                          |
| ISAM       | NO      | Obsolete storage engine                                        |
+------------+---------+----------------------------------------------------------------+
12 rows in set (0.00 sec)

mysql>

通过上面我们可以发现,默认的数据库引擎是MyISAM ,在support中显示为YES的为支持,NO为不支持,DEFAULT为默认,DISABLED为关闭,InooDB可以在my.cnf中配置开启

MySQL不设置的情况下,一般默认引擎为MyISAM
修改/etc/my.cnf配置文件
[mysqld]
#set default storage engine for the InnoDB,or for the MyISAM.
#Sunrier
default-storage-engine=InnoDB
default_table_type=InnoDB

#Sunrier
#数据文件存放路径
innodb_data_home_dir=/var/lib/mysql/

#Sunrier
#数据文件初始化大小为10M,并允许它自扩充
innodb_data_file_path=ibdata1:10M:autoextend

#日志文件存放路径
innodb_log_group_home_dir=/var/lib/mysql/

#下面InnoDB引擎设置可选项

# You can set .._buffer_pool_size up to 50 - 80 %
# of RAM but beware of setting memory usage too high
#innodb_buffer_pool_size = 16M
#innodb_additional_mem_pool_size = 2M
# Set .._log_file_size to 25 % of buffer pool size
#innodb_log_file_size = 5M
#innodb_log_buffer_size = 8M
#innodb_flush_log_at_trx_commit = 1
#innodb_lock_wait_timeout = 50

innodb_buffer_pool_size
定义了InnoDB 存储引擎的表数据和索引数据的最大内存缓冲区大小.和MyISAM 存储引擎不同,MyISAM 的 key_buffer_size 只能缓存索引键,而innodb_buffer_pool_size 却可以缓存数据块和索引键.适当的增加这个参数的大小,可以有效的减少InnoDB 类型的表的磁盘 I/O.在一个以 InnoDB为主的专用数据库服务器上,可以考虑把该参数设置为物理内存大小的 60%-80% 。

innodb_additional_mem_pool_size
这个参数用来设置 InnoDB 存储的数据目录信息和其它内部数据结构的内存池大小.应用程序里的表越多,你需要在这里分配越多的内存.对于一个相对稳定的应用,这个参数的大小也是相对稳定的,也没有必要预留非常大的值.如果InnoDB 用光了这个池内的内存,InnoDB开始从操作系统分配内存,并且往MySQL错误日志写警告信息.默认值是1MB,当发现错误日志中已经有相关的警告信息时,就应该适当的增加该参数的大小。

innodb_log_buffer_size
这个参数设置 InnoDB 用来往磁盘上的日志文件写操作的缓冲区的大小.这有点像 Oracle 的 log_buffer,通过内存缓冲来延缓磁盘 I/O 以提高访问的效率. 因为MySQL每秒都会将日志缓冲区的内容刷新到日志文件,因此无需设置超过 1 秒所需的内存空间.通常设置为 8 ~ 16MB 就足够了,默认值是1MB

修改/etc/my.cnf配置文件,重启MySQL后,再次查看数据库引擎

mysql> show engines;
+------------+---------+----------------------------------------------------------------+
| Engine     | Support | Comment                                                        |
+------------+---------+----------------------------------------------------------------+
| MyISAM     | YES     | Default engine as of MySQL 3.23 with great performance         |
| MEMORY     | YES     | Hash based, stored in memory, useful for temporary tables      |
| InnoDB     | DEFAULT | Supports transactions, row-level locking, and foreign keys     |
| BerkeleyDB | YES     | Supports transactions and page-level locking                   |
| BLACKHOLE  | NO      | /dev/null storage engine (anything you write to it disappears) |
| EXAMPLE    | NO      | Example storage engine                                         |
| ARCHIVE    | NO      | Archive storage engine                                         |
| CSV        | NO      | CSV storage engine                                             |
| ndbcluster | NO      | Clustered, fault-tolerant, memory-based tables                 |
| FEDERATED  | NO      | Federated MySQL storage engine                                 |
| MRG_MYISAM | YES     | Collection of identical MyISAM tables                          |
| ISAM       | NO      | Obsolete storage engine                                        |
+------------+---------+----------------------------------------------------------------+
12 rows in set (0.00 sec)

mysql>

九、设置最大连接数,默认是100 ,修改为30
修改/etc/my.cnf配置文件
[mysqld]
max_connections=30

保存后重启MySQL,查看设置是否生效:
[Sunrier@localhost MySql]$ mysql -uroot -predhat
Welcome to the MySQL monitor.  Commands end with ; or g.
Your MySQL connection id is 23 to server version: 5.0.22

Type 'help;' or 'h' for help. Type 'c' to clear the buffer.

mysql> show variables like 'max_con_%';
+--------------------+-------+
| Variable_name      | Value |
+--------------------+-------+
| max_connect_errors | 10    |
| max_connections    | 30|
+--------------------+-------+
2 rows in set (0.01 sec)

mysql>

相关知识补充(2012.05.16):

MySQL清除当前屏幕命令

mysql> system clear;


Linux下MySQL的几个重要目录
1)数据库目录
/var/lib/mysql/
2)配置文件
/usr/share/mysql(mysql.server命令及配置文件)
3)相关命令
/usr/bin(mysqladmin mysqldump等命令)
4)启动脚本
/etc/rc.d/init.d/(启动脚本文件mysql的目录)


MySQL服务的启动与关闭:
启动:service mysqld start
在启动文件中去启动:/etc/init.d/mysqld start
重启:service mysqld restart
停止:service mysqld stop
停止:mysqladmin -uroot -predhat shutdown

查看Mysql服务是否已经启动,看Mysql端口是否打开,Mysql默认的端口是3306
netstat -nat
[root@localhost MySql]# netstat -nat
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address               Foreign Address             State     
tcp        0      0 127.0.0.1:2208              0.0.0.0:*                   LISTEN     
tcp        0      0 0.0.0.0:3306                0.0.0.0:*                   LISTEN     
tcp        0      0 0.0.0.0:523                 0.0.0.0:*                   LISTEN     
tcp        0      0 0.0.0.0:111                 0.0.0.0:*                   LISTEN     
tcp        0      0 0.0.0.0:50000               0.0.0.0:*                   LISTEN     
tcp        0      0 0.0.0.0:1015                0.0.0.0:*                   LISTEN     
tcp        0      0 127.0.0.1:631               0.0.0.0:*                   LISTEN     
tcp        0      0 127.0.0.1:25                0.0.0.0:*                   LISTEN     
tcp        0      0 127.0.0.1:2207              0.0.0.0:*                   LISTEN     
tcp        0      0 :::22                       :::*                        LISTEN     
[root@localhost MySql]#

修改MySQL目录步骤:
MySQL默认的数据文件存储目录为/var/lib/mysql。假如要放到/home目录的sunrier/data下,如/home/sunrier/data下需要进行下面几步:
1)在/home/sunrier目录下建立data目录(此时我的home目录下的sunrier目录已经存在)
[root@localhost ~]# cd /home/sunrier
[root@localhost sunrier]# mkdir data


2)把MySQL服务进程停掉:
[root@localhost sunrier]# service mysqld stop
停止 MySQL:     [确定]
[root@localhost sunrier]#



3)把/var/lib/mysql整个目录移到/home/sunrier/data
[root@localhost sunrier]# mv /var/lib/mysql /home/sunrier/data
[root@localhost sunrier]#



4)查找/etc/my.cnf配置文件
如果/etc/目录下没有my.cnf配置文件,到/usr/share/mysql/下找到my-medium.cnf文件,拷贝其中一个到/etc/并改名为my.cnf。
命令如下:
[root@localhost sunrier]# cp /usr/share/mysql/my-medium.cnf /etc/my.cnf
如果在/usr/share/mysql/下没有my-medium.cnf.cnf文件,你可以用命令查找下my-medium.cnf文件所在位置,然后拷贝过去
[root@localhost sunrier]# find / -name my-medium.cnf
/usr/share/doc/mysql-server-5.0.22/my-medium.cnf
[root@localhost sunrier]# cp /usr/share/doc/mysql-server-5.0.22/my-medium.cnf /etc/my.cnf
[root@localhost sunrier]#



5)修改MySQL的配置文件/etc/my.cnf
为保证MySQL能够正常启动工作,需要指明mysql.sock文件的产生位置.修改socket=/var/lib/mysql/mysql.sock一行中等号右边的值为:/home/sunrier/data/mysql/mysql.sock
操作如下:
[mysqld]
#socket=/var/lib/mysql/mysql.sock
socket=/home/sunrier/data/mysql/mysql.sock


修改数据存放路径为实际当前路径
#datadir=/var/lib/mysql
datadir=/home/sunrier/data/mysql


6)重新启动MySQL服务
[root@localhost sunrier]#service mysqld restart
或用reboot命令重启Linux
如果工作正常移动就成功了,否则对照前面的6步再检查一下。如果有问题还是检查不出来,再百度,google或者咨询其他相关人员


声明: 此文观点不代表本站立场;转载须要保留原文链接;版权疑问请联系我们。