search
HomeDatabaseMysql Tutorial在centos 下安装和使用MySQL

在centos 下安装和使用MySQL

Jun 07, 2016 pm 03:46 PM
centoslinuxmysqluseInstallintroduction

一、引言 想使用Linux已经很长时间了,由于没有硬性任务一直也没有系统学习,近日由于工作需要必须使用Linux下的MySQL。本以为有Windows下使用SQL Server的经验,觉得在Linux下安装MySql应该是易如反掌的事,可在真正安装和使用MySQL时走了很多弯路,遇见很

一、引言  想使用Linux已经很长时间了,由于没有硬性任务一直也没有系统学习,近日由于工作需要必须使用Linux下的MySQL。本以为有 Windows下使用SQL Server的经验,觉得在Linux下安装MySql应该是易如反掌的事,可在真正安装和使用MySQL时走了很多弯路,遇见很多问题,毕竟Linux 和Windows本身就有很大区别。为了让和我一样的初学者在学习的过程中少走弯路,尽快入门,写了此文,希望对您有所帮助。本文的Linux环境是 Red Hat 9.0,MySQL是4.0.16。  

二、安装Mysql   

1、下载MySQL的安装文件  

安装MySQL需要下面两个文件:  

MySQL-server-4.0.16-0.i386.rpm      

MySQL-client-4.0.16-0.i386.rpm   

下载地址为:http://www.mysql.com/downloads/mysql-4.0.html, 打开此网页,下拉网页找到“Linux x86 RPM downloads”项,找到“Server”和“Client programs”项,下载需要的上述两个rpm文件。  

2、安装MySQL   

rpm文件是Red Hat公司开发的软件安装包,rpm可让Linux在安装软件包时免除许多复杂的手续。

该命令在安装时常用的参数是 –ivh ,其中i表示将安装指定的rmp软件包,V表示安装时的详细信息,h表示在安装期间出现“#”符号来显示目前的安装过程。这个符号将持续到安装完成后才停 止。  

1)安装服务器端  

在有两个rmp文件的目录下运行如下命令: 

 [root@test1 local]# rpm -ivh MySQL-server-4.0.16-0.i386.rpm   

显示如下信息。   

 warning: MySQL-server-4.0.16-0.i386.rpm: V3 DSA signature: NOKEY, key ID 5072e1f5   

Preparing...       ########################################### [100%]   1:MySQL-server     ########################################### [100%]    。。。。。。(省略显示)  

/usr/bin/mysqladmin -u root password 'new-password'   

/usr/bin/mysqladmin -u root -h test1 password 'new-password'    。。。。。。(省略显示)  

Starting mysqld daemon with databases from /var/lib/mysql   

如出现如上信息,服务端安装完毕。测试是否成功可运行netstat看Mysql端口是否打开,如打开表示服务已经启动,安装成功。Mysql默认 的端口是3306。  

[root@test1 local]# netstat -nat   

Active Internet connections (servers and established)   

Proto Recv-Q Send-Q Local Address      Foreign Address     State     tcp

  0  0 0.0.0.0:3306     0.0.0.0:*      LISTEN     

上面显示可以看出MySQL服务已经启动。  

2)安装客户端  

运行如下命令:  

[root@test1 local]# rpm -ivh MySQL-client-4.0.16-0.i386.rpm   

warning: MySQL-client-4.0.16-0.i386.rpm: V3 DSA signature: NOKEY, key ID 5072e1f5   

Preparing...    ########################################### [100%]   1:MySQL-client  ########################################### [100%]  

 显示安装完毕。  

用下面的命令连接mysql,测试是否成功。 

三、登录MySQL   

登录MySQL的命令是mysql, mysql 的使用语法如下:   

mysql [-u username] [-h host] [-p[password]] [dbname]   

username 与 password 分别是 MySQL 的用户名与密码,mysql的初始管理帐号是root,没有密码,注意:这个root用户不是Linux的系统用户。MySQL默认用户是root,由于 初始没有密码,第一次进时只需键入mysql即可。

   [root@test1 local]# mysql   Welcome to the MySQL monitor. Commands end with ; or /g.   Your MySQL connection id is 1 to server version: 4.0.16-standard   Type 'help;' or '/h' for help. Type '/c' to clear the buffer.   

mysql>   出现了“mysql>”提示符,恭喜你,安装成功!  

增加了密码后的登录格式如下:  

mysql -u root -p   Enter password: (输入密码)   其中-u后跟的是用户名,-p要求输入密码,回车后在输入密码处输入密码。  

注意:这个mysql文件在/usr/bin目录下,与后面讲的启动文件/etc/init.d/mysql不是一个文件。  

四、MySQL的几个重要目录  

MySQL安装完成后不象SQL Server默认安装在一个目录,它的数据库文件、配置文件和命令文件分别在不同的目录,了解这些目录非常重要,尤其对于Linux的初学者,因为 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默认没有密码,安装完毕增加密码的重要性是不言而喻的。  

1、命令  usr/bin/mysqladmin -u root password 'new-password'   

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

2、例子  例1:给root加个密码123456。  

键入以下命令 :  [root@test1 local]# /usr/bin/mysqladmin -u root password 123456   

注:因为开始时root没有密码,所以-p旧密码一项就可以省略了。  

3、测试是否修改成功  

1)不用密码登录  

[root@test1 local]# mysql   

ERROR 1045: Access denied for user: 'root@localhost' (Using password: NO)   显示错误,说明密码已经修改。  

2)用修改后的密码登录  

[root@test1 local]# mysql -u root -p   

Enter password: (输入修改后的密码123456)   

Welcome to the MySQL monitor. Commands end with ; or /g.   

Your MySQL connection id is 4 to server version: 4.0.16-standard   

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

mysql>   成功!  

这是通过mysqladmin命令修改口令,也可通过修改库来更改口令。  

六、启动与停止  

1、启动  MySQL安装完成后启动文件mysql在/etc/init.d目录下,在需要启动时运行下面命令即可。  

[root@test1 init.d]# /etc/init.d/mysqld start   

2、停止  /usr/bin/mysqladmin -u root -p shutdown   

3、自动启动  

1)察看mysql是否在自动启动列表中  

[root@test1 local]# /sbin/chkconfig –list   

2)把MySQL添加到你系统的启动服务组里面去  

[root@test1 local]# /sbin/chkconfig – add mysql   

3)把MySQL从启动服务组里面删除。  

[root@test1 local]# /sbin/chkconfig – del mysql

七、更改MySQL目录  

MySQL默认的数据文件存储目录为/var/lib/mysql。

假如要把目录移到/home/data下需要进行下面几步:  

1、home目录下建立data目录  cd /home   mkdir data   

2、把MySQL服务进程停掉:   mysqladmin -u root -p shutdown   

3、把/var/lib/mysql整个目录移到/home/data   mv /var/lib/mysql /home/data/   

这样就把MySQL的数据文件移动到了/home/data/mysql下  

4、找到my.cnf配置文件  

如果/etc/目录下没有my.cnf配置文件,请到/usr/share/mysql/下找到*.cnf文件,拷贝其中一个到/etc/并改名为 my.cnf)中。

命令如下:  

[root@test1 mysql]# cp /usr/share/mysql/my-medium.cnf /etc/my.cnf   

5、编辑MySQL的配置文件/etc/my.cnf   

为保证MySQL能够正常工作,需要指明mysql.sock文件的产生位置。

修改socket=/var/lib/mysql/mysql.sock一行中等号右边的值为:/home/mysql/mysql.sock 。

操作如下:  

vi  my.cnf   

(用vi工具编辑my.cnf文件,找到下列数据修改之)   

# The MySQL server     [mysqld]    

port   = 3306    

#socket  = /var/lib/mysql/mysql.sock(原内容,为了更稳妥用“#”注释此行)   

socket  = /home/data/mysql/mysql.sock   (加上此行)  

6、修改MySQL启动脚本/etc/rc.d/init.d/mysql   

最后,需要修改MySQL启动脚本/etc/rc.d/init.d/mysql,把其中datadir=/var/lib/mysql一行中,等 号右边的路径改成你现在的实际存放路径:home/data/mysql。  

[root@test1 etc]# vi /etc/rc.d/init.d/mysql   

#datadir=/var/lib/mysql    (注释此行)  

datadir=/home/data/mysql   (加上此行)  

7、重新启动MySQL服务  

/etc/rc.d/init.d/mysql start   

或用reboot命令重启Linux   

如果工作正常移动就成功了,否则对照前面的7步再检查一下。  

八、MySQL的常用操作  

注意:MySQL中每个命令后都要以分号;结尾。  

1、显示数据库  

mysql> show databases;   

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

| Database |   

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

| mysql  |   

| test   |   

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

2 rows in set (0.04 sec)   

Mysql刚安装完有两个数据库:mysql和test。mysql库非常重要,它里面有MySQL的系统信息,我们改密码和新增用户,实际上就是 用这个库中的相关表进行操作。  

2、显示数据库中的表  

mysql> use mysql; (打开库,对每个库进行操作就要打开此库,类似于foxpro )  

Database changed   

mysql> show tables;   

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

| Tables_in_mysql |   

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

| columns_priv  |   

| db       |   

| func      |   

| host      |   

| tables_priv   |   

| user      |   

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

6 rows in set (0.01 sec)   

3、显示数据表的结构:   

describe 表名;   

4、显示表中的记录:   

select * from 表名;   

例如:显示mysql库中user表中的纪录。

所有能对MySQL用户操作的用户都在此表中。  

Select * from user;   

5、建库:   

create database 库名;   

例如:创建一个名字位aaa的库  

mysql> create databases aaa;

6、建表:   

use 库名;   

create table 表名 (字段设定列表);  

例如:在刚创建的aaa库中建立表name,表中有id(序号,自动增长),xm(姓名),xb(性别),csny(出身年月)四个字段  

use aaa;   

mysql> create table name (id int(3) auto_increment not null primary key, xm char(8),xb char(2),csny date);   

可以用describe命令察看刚建立的表结构。  

mysql> describe name;   

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

| Field | Type  | Null | Key | Default | Extra     |   

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

| id  | int(3) |   | PRI | NULL  | auto_increment |   

| xm  | char(8) | YES |   | NULL  |        |   

| xb  | char(2) | YES |   | NULL  |        |   

| csny | date  | YES |   | NULL  |        |   

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

7、增加记录  

例如:增加几条相关纪录。  

mysql> insert into name values('','张三','男','1971-10-01');   

mysql> insert into name values('','白云','女','1972-05-20');   

可用select命令来验证结果。  

mysql> select * from name;   

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

| id | xm  | xb  | csny    |   

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

| 1 | 张三 | 男  | 1971-10-01 |   

| 2 | 白云 | 女  | 1972-05-20 |   

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

8、修改纪录  

例如:将张三的出生年月改为1971-01-10   

mysql> update name set csny='1971-01-10' where xm='张三';   

9、删除纪录  

例如:删除张三的纪录。  

mysql> delete from name where xm='张三';   

10、删库和删表   

drop database 库名;   

drop table 表名;  

九、增加MySQL用户  

格式:grant select on 数据库.* to 用户名@登录主机 identified by "密码"

例1、增加一个用户user_1密码为123,让他可以在任何主机上登录,并对所有数据库有查询、插入、修改、删除的权限。首先用以root用户连 入MySQL,然后键入以下命令:  

mysql> grant select,insert,update,delete on *.* to user_1@"%" Identified by "123"; 例1增加的用户是十分危险的,如果知道了user_1的密码,那么他就可以在网上的任何一台电脑上登录你的MySQL数据库并对你的数据为所欲为了,解决 办法见例2。  

例2、增加一个用户user_2密码为123,让此用户只可以在localhost上登录,并可以对数据库aaa进行查询、插入、修改、删除的操作 (localhost指本地主机,即MySQL数据库所在的那台主机),这样用户即使用知道user_2的密码,他也无法从网上直接访问数据库,只能通过 MYSQL主机来操作aaa库。  

mysql>grant select,insert,update,delete on aaa.* to user_2@localhost identified by "123";   

用新增的用户如果登录不了MySQL,

在登录时用如下命令:  mysql -u user_1 -p -h 192.168.113.50 (-h后跟的是要登录主机的ip地址)  

十、备份与恢复  

1、备份  例如:将上例创建的aaa库备份到文件back_aaa中  

[root@test1 root]# cd /home/data/mysql (进入到库目录,本例库已由val/lib/mysql转到/home/data/mysql,见上述第七部分 内容)   

[root@test1 mysql]# mysqldump -u root -p --opt aaa > back_aaa   

2、恢复  [root@test mysql]# mysql -u root -p ccc

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What Are the Limitations of Using Views in MySQL?What Are the Limitations of Using Views in MySQL?May 14, 2025 am 12:10 AM

MySQLviewshavelimitations:1)Theydon'tsupportallSQLoperations,restrictingdatamanipulationthroughviewswithjoinsorsubqueries.2)Theycanimpactperformance,especiallywithcomplexqueriesorlargedatasets.3)Viewsdon'tstoredata,potentiallyleadingtooutdatedinforma

Securing Your MySQL Database: Adding Users and Granting PrivilegesSecuring Your MySQL Database: Adding Users and Granting PrivilegesMay 14, 2025 am 12:09 AM

ProperusermanagementinMySQLiscrucialforenhancingsecurityandensuringefficientdatabaseoperation.1)UseCREATEUSERtoaddusers,specifyingconnectionsourcewith@'localhost'or@'%'.2)GrantspecificprivilegeswithGRANT,usingleastprivilegeprincipletominimizerisks.3)

What Factors Influence the Number of Triggers I Can Use in MySQL?What Factors Influence the Number of Triggers I Can Use in MySQL?May 14, 2025 am 12:08 AM

MySQLdoesn'timposeahardlimitontriggers,butpracticalfactorsdeterminetheireffectiveuse:1)Serverconfigurationimpactstriggermanagement;2)Complextriggersincreasesystemload;3)Largertablesslowtriggerperformance;4)Highconcurrencycancausetriggercontention;5)M

MySQL: Is it safe to store BLOB?MySQL: Is it safe to store BLOB?May 14, 2025 am 12:07 AM

Yes,it'ssafetostoreBLOBdatainMySQL,butconsiderthesefactors:1)StorageSpace:BLOBscanconsumesignificantspace,potentiallyincreasingcostsandslowingperformance.2)Performance:LargerrowsizesduetoBLOBsmayslowdownqueries.3)BackupandRecovery:Theseprocessescanbe

MySQL: Adding a user through a PHP web interfaceMySQL: Adding a user through a PHP web interfaceMay 14, 2025 am 12:04 AM

Adding MySQL users through the PHP web interface can use MySQLi extensions. The steps are as follows: 1. Connect to the MySQL database and use the MySQLi extension. 2. Create a user, use the CREATEUSER statement, and use the PASSWORD() function to encrypt the password. 3. Prevent SQL injection and use the mysqli_real_escape_string() function to process user input. 4. Assign permissions to new users and use the GRANT statement.

MySQL: BLOB and other no-sql storage, what are the differences?MySQL: BLOB and other no-sql storage, what are the differences?May 13, 2025 am 12:14 AM

MySQL'sBLOBissuitableforstoringbinarydatawithinarelationaldatabase,whileNoSQLoptionslikeMongoDB,Redis,andCassandraofferflexible,scalablesolutionsforunstructureddata.BLOBissimplerbutcanslowdownperformancewithlargedata;NoSQLprovidesbetterscalabilityand

MySQL Add User: Syntax, Options, and Security Best PracticesMySQL Add User: Syntax, Options, and Security Best PracticesMay 13, 2025 am 12:12 AM

ToaddauserinMySQL,use:CREATEUSER'username'@'host'IDENTIFIEDBY'password';Here'showtodoitsecurely:1)Choosethehostcarefullytocontrolaccess.2)SetresourcelimitswithoptionslikeMAX_QUERIES_PER_HOUR.3)Usestrong,uniquepasswords.4)EnforceSSL/TLSconnectionswith

MySQL: How to avoid String Data Types common mistakes?MySQL: How to avoid String Data Types common mistakes?May 13, 2025 am 12:09 AM

ToavoidcommonmistakeswithstringdatatypesinMySQL,understandstringtypenuances,choosetherighttype,andmanageencodingandcollationsettingseffectively.1)UseCHARforfixed-lengthstrings,VARCHARforvariable-length,andTEXT/BLOBforlargerdata.2)Setcorrectcharacters

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor