标签: MySQL

  • 每天自动备份mysql数据库并发送到Email

    每天自动备份mysql数据库的脚本,并且自动发送到你指定的邮箱面,这样vpser再也不会为丢失数据烦恼啦。

     

    mysqldump -uuser -ppassword –databases db1 db2 db3 > /home/website/backups/databackup.sql

    tar zcf /home/website/backups/databackup.sql.tar.gz /home/website/backups/

    echo “主题:数据库备份” | mutt -a /home/website/backups/databackup.sql.tar.gz -s “内容:数据库备份” 你的邮箱

    rm -r /home/website/backups/*

     

    将上面的代码保存为automysqlbackup.sh

    然后利用crontab 实现自动备份,在ssh下运行,

     

    crontab -e

     

    输入以下内容:

     

    00 00 * * * /存放位置/automysqlbackup.sh

     

    这样就实现了每天00:00自动备份mysql数据库并发送到Email

    简单的说明下吧:

    第一句是一次性备份多个数据库,这个要你用root权限的用户才可以的..-u后面的是数据库用户名 -p后面的是数据库密码 无需空格 db1 db2 db3为你需要备份的数据库名。

    如果你的数据库用户名没有root这个权限,可以改为这样

     

    mysqldump -uuser -ppassword db1 > /home/website/backups/db1.sql

    mysqldump -uuser -ppassword db2 > /home/website/backups/db1.sql

    mysqldump -uuser -ppassword db3 > /home/website/backups/db1.sql

     

    第二句是将 backups 文件夹里面的数据文件压缩为文件名:databackup.sql.tar.gz

    第三句是将压缩了的数据库文件发送到指定的邮箱…..

    其中的主题:数据库备份,就是邮件的主题,内容:数据库备份,就是邮件的内用,

    /home/website/backups/databackup.sql.tar.gz 为附件

  • mysql命令行下用户管理

    mysql安装后好,会有一个名字为mysql的数据库,存放用户的表是user,mysql数据库的用户管理就是围绕这个表展开的,当然还有一些表,例如:tables_priv,procs_priv,clumns_priv,information_schema数据库里面的USER_PRIVILEGES等。

    安装完成后,如果需要远程连接,可以这样:

    1、MYSQL服务器上:

    比如:

    C:\>mysql -uroot -p

    Enter password: ******

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

    Your MySQL connection id is 2

    Server version: 5.1.22-rc-community-log MySQL Community Server (GPL)

    Type ‘help;’ or ‘\h’ for help. Type ‘\c’ to clear the buffer.

    mysql> grant all privileges on *.* to ‘yourname’@’%’ identified by ‘youpasswd’;

    Query OK, 0 rows affected (0.05 sec)

    mysql> flush privileges;

    Query OK, 0 rows affected (0.06 sec)

    mysql> exit

    Bye

    再把/etc/mysql/my.cnf中的bind-address=127.0.0.1注释了就可以远程连接了。

    grant 权限名(sqlserver和mysql不一样的,可以看手册知道,分所有的权限用all) on 库名(*表全部).表名 to 要授权的用户名@”%”(%表示所有的IP,可以只些一个IP) identified by “密码”;

    例: grant all privileges on *.* to root@”%” identified by “密码”;

    查询mysql所有用户名: select user,host,password from mysql.user;

    如果有mysql管理工具phpmyadmin的话,我们可以通过图形画界面来对用户进行管理,但是如果没有phpmyadmin这样的管理工具怎么办呢?这个时候,我们可以通过命令行执行sql语句来管理mysql的用户。

    一,添加用户

    1,create database user

    语法:

    CREATE DATABASE USER user_specification

    [, user_specification] …

    user_specification:

    user [IDENTIFIED BY [PASSWORD] ‘password’]

    实例:

    mysql> create user ’44’@’127.0.0.1′; //创建一个44用户

    Query OK, 0 rows affected (0.00 sec)

     

    mysql> create user ’33’@’localhost’ identified by ‘aaaa’; //创建一个33用户,密码为aaaa

    Query OK, 0 rows affected (0.00 sec)

     

    mysql> select * from mysql.user where user=’33’ or user=’44’\G; //查看一下mysql下的user

    create user 虽然可以创建用户,但是它只是创建用户,并没有给用户分配置权限,所以一般被 grant命令所取代。

    2,grant

    语法:

    GRANT

    priv_type [(column_list)]

    [, priv_type [(column_list)]] …

    ON [object_type] priv_level

    TO user_specification [, user_specification] …

    [REQUIRE {NONE | ssl_option [[AND] ssl_option] …}]

    [WITH with_option …]

     

    object_type:

    TABLE

    | FUNCTION

    | PROCEDURE

     

    priv_level:

    *

    | *.*

    | db_name.*

    | db_name.tbl_name

    | tbl_name

    | db_name.routine_name

     

    user_specification:

    user [IDENTIFIED BY [PASSWORD] ‘password’]

     ssl_option:

    SSL

    | X509 #要求x509证书

    | CIPHER ‘cipher’ #加密算法

    | ISSUER ‘issuer’ #证书发行商

    | SUBJECT ‘subject’ #主题

     

    with_option:

    GRANT OPTION

    | MAX_QUERIES_PER_HOUR count #每小时最多执行多少条sql

    | MAX_UPDATES_PER_HOUR count #每小时最多更新多少条数据

    | MAX_CONNECTIONS_PER_HOUR count #每小时最大的联接数是多少

    | MAX_USER_CONNECTIONS count #最大用户联接数

    不要被上面的语法吓倒,其实理解什么意思,就很容易掌握。我是这样理解的。

    grant 权限 on 应用范围(数据库表,方法等) to 用户(用@隔开,前面是用户名后面是主机名’用户名’@’主机名’) identified by 密码 require 要求什么的 with 对用户的进行的执行sql的条数控制。

    个人觉得,只要记得上面几个红色的关键词,基本上这个命令就掌握了。

    Privilege Meaning
    ALL [PRIVILEGES] 所有权限
    ALTER 可以使用alter table
    ALTER ROUTINE 可以使用alter routine
    CREATE 可以创建数据库和表
    CREATE ROUTINE 可以使用create routine
    CREATE TEMPORARY TABLES 可以使用临时表
    CREATE USER 可以对用户进添加,删除,重命名,撤销权限
    CREATE VIEW 可以创建和修改视图
    DELETE 可以删除数据
    DROP 可能删除数据库,表,视图等
    EVENT 可以使用事件高度器
    EXECUTE 可以执行routine
    FILE 可以在服务器读写文件
    GRANT OPTION 用户有权对自己添加的用衣授权
    INDEX 可以创建,删除索引
    INSERT 可以插入
    LOCK TABLES 可以锁定表
    PROCESS 可以使用SHOW PROCESSLIST来查看mysql当前用户的执行sql情况
    REFERENCES Not implemented
    RELOAD 可以使用刷新功能
    REPLICATION CLIENT 用户可以进行主从同步
    REPLICATION SLAVE 主从同步时,从服务器可以从主服务器读取binary log
    SELECT 可以查找
    SHOW DATABASES 可以使用show databases来查看所有数据库
    SHOW VIEW 可以使用show view来查看视图
    SHUTDOWN 可以使用mysqladmin中的参数shutdown
    SUPER Enable use of other adminstrative operations such as CHANGE MASTER TO, KILL, PURGE BINARY LOGS, SET GLOBAL, and mysqladmin debug command
    TRIGGER 可以使用触发器
    UPDATE 可以进行理会新操作
    USAGE 无特权

    实例:

    grant all ON test.* TO ‘test’@’localhost’; //test用户拥有test数据库下的所有操作

    grant select,update on test.user to ‘test’@’localhost’; //test用户可以对test数据库下user表,进行查找和更新操作

    //test用户的的密码是111111,对user表中的name字段有读取权限,对id,name有更新权限

    grant select(name),update(id,name) on test.user to ‘test’@’localhost’ identified by ‘111111’;

    //test用户对所有数据库拥有所有权力,并且要求ssl加密

    grant all privileges on *.* to ‘test’@’%’ identified by ‘123456’ require ssl

    当添加完用户后,别忘 了 flush privileges;

    二,删除用户

    语法:

    DROP USER user [, user] …

    实例:

    drop user ‘test2’@’localhost’; //当用drop删除用户进,tables_priv,procs_priv等表中的数据也会被删除

    在这里为什么要用’test2’@’localhost’当用户名,而不是直接test2呢,因为mysql.user这张表,是根用户名和host名决定一个用户,你可查看一下表结构就知道了。

    show create table mysql.user\G;你会发现有这个东西PRIMARY KEY (`Host`,`User`),表示联合主键

    三,修改用户

    语法:

    RENAME USER old_user TO new_user

    [, old_user TO new_user] …

    实例:

    rename user ‘test2’@’localhost’ to ‘test’@’%’;

    四,修改权限

    语法:

    REVOKE

    priv_type [(column_list)]

    [, priv_type [(column_list)]] …

    ON [object_type] priv_level

    FROM user [, user] …

    REVOKE ALL PRIVILEGES, GRANT OPTION

     

    FROM user [, user] …

    grant就给用户分配权限,revoke是把权限从用户的身上拿走。

    实例:

    mysql> revoke update on *.* from ‘tank’@’localhost’;

    Query OK, 0 rows affected (0.00 sec)

     mysql> select mysql.user.update_priv from mysql.user where user=’tank’ and host=’localhost’;

    +————-+

    | update_priv |

    +————-+

    | N |

    +————-+

    1 row in set (0.00 sec)

    去掉tank@localhost这个用户的更新功能,这个是去掉一个权限,如果我要全部去掉怎么办呢,一个一个写太麻烦了,看下面的一个例子

    mysql> revoke all privileges ,grant option from ’33’@’localhost’;

    Query OK, 0 rows affected (0.00 sec)

    mysql> flush privileges;

    Query OK, 0 rows affected (0.01 sec)

    用掉33@localhost这个用户的所有权限

  • MYSQL常用命令

    1.导出整个数据库

    mysqldump -u 用户名 -p –default-character-set=latin1 数据库名 > 导出的文件名(数据库默认编码是latin1)

    mysqldump -u wcnc -p smgp_apps_wcnc > wcnc.sql

    2.导出一个表

    mysqldump -u 用户名 -p 数据库名 表名> 导出的文件名

    mysqldump -u wcnc -p smgp_apps_wcnc users> wcnc_users.sql

    3.导出一个数据库结构

    mysqldump -u wcnc -p -d –add-drop-table smgp_apps_wcnc >d:wcnc_db.sql

    -d 没有数据 –add-drop-table 在每个create语句之前增加一个drop table

    4.导入数据库

    A:常用source 命令

    进入mysql数据库控制台,

    如mysql -u root -p

    mysql>use 数据库

    然后使用source命令,后面参数为脚本文件(如这里用到的.sql)

    mysql>source wcnc_db.sql

     

    B:使用mysqldump命令

     

    mysqldump -u username -p dbname < filename.sql

     

    C:使用mysql命令

     

    mysql -u username -p -D dbname < filename.sql

     

    一、启动与退出

    1、进入MySQL:启动MySQL Command Line Client(MySQL的DOS界面),直接输入安装时的密码即可。此时的提示符是:mysql>

    2、退出MySQL:quit或exit

    二、库操作

    1、、创建数据库

    命令:create database <数据库名>

    例如:建立一个名为xhkdb的数据库

    mysql> create database xhkdb;

    2、显示所有的数据库

    命令:show databases (注意:最后有个s)

    mysql> show databases;

    3、删除数据库

    命令:drop database <数据库名>

    例如:删除名为 xhkdb的数据库

    mysql> drop database xhkdb;

    4、连接数据库

    命令: use <数据库名>

    例如:如果xhkdb数据库存在,尝试存取它:

    mysql> use xhkdb;

    屏幕提示:Database changed

    5、查看当前使用的数据库

    mysql> select database();

     

    6、当前数据库包含的表信息:

    mysql> show tables; (注意:最后有个s)

     

    三、表操作,操作之前应连接某个数据库

    1、建表

    命令:create table <表名> ( <字段名1> <类型1> [,..<字段名n> <类型n>]);

     

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

    2、获取表结构

    命令: desc 表名,或者show columns from 表名

    mysql>DESCRIBE MyClass

    mysql> desc MyClass;

    mysql> show columns from MyClass;

    3、删除表

    命令:drop table <表名>

    例如:删除表名为 MyClass 的表

    mysql> drop table MyClass;

    4、插入数据

    命令:insert into <表名> [( <字段名1>[,..<字段名n > ])] values ( 值1 )[, ( 值n )]

    例如,往表 MyClass中插入二条记录, 这二条记录表示:编号为1的名为Tom的成绩为96.45, 编号为2 的名为Joan 的成绩为82.99,编号为3 的名为Wang 的成绩为96.5.

    mysql> insert into MyClass values(1,’Tom’,96.45),(2,’Joan’,82.99), (2,’Wang’, 96.59);

    5、查询表中的数据

    1)、查询所有行

    命令: select <字段1,字段2,…> from < 表名 > where < 表达式 >

    例如:查看表 MyClass 中所有数据

    mysql> select * from MyClass;

    2)、查询前几行数据

    例如:查看表 MyClass 中前2行数据

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

     

    或者:

     

    mysql> select * from MyClass limit 0,2;

    6、删除表中数据

    命令:delete from 表名 where 表达式

    例如:删除表 MyClass中编号为1 的记录

    mysql> delete from MyClass where id=1;

    7、修改表中数据:update 表名 set 字段=新值,… where 条件

    mysql> update MyClass set name=’Mary’ where id=1;

    7、在表中增加字段:

     

    命令:alter table 表名 add字段 类型 其他;

    例如:在表MyClass中添加了一个字段passtest,类型为int(4),默认值为0

    mysql> alter table MyClass add passtest int(4) default ‘0’

    8、更改表名:

    命令:rename table 原表名 to 新表名;

    例如:在表MyClass名字更改为YouClass

    mysql> rename table MyClass to YouClass;

     

    更新字段内容

    update 表名 set 字段名 = 新内容

    update 表名 set 字段名 = replace(字段名,’旧内容’,’新内容’);

     

    文章前面加入4个空格

    update article set content=concat(‘  ’,content);

     

    字段类型

    1.INT[(M)] 型: 正常大小整数类型

    2.DOUBLE[(M,D)] [ZEROFILL] 型: 正常大小(双精密)浮点数字类型

    3.DATE 日期类型:支持的范围是1000-01-01到9999-12-31。MySQL以YYYY-MM-DD格式来显示DATE值,但是允许你使用字符串或数字把值赋给DATE列

    4.CHAR(M) 型:定长字符串类型,当存储时,总是是用空格填满右边到指定的长度

    5.BLOB TEXT类型,最大长度为65535(2^16-1)个字符。

    6.VARCHAR型:变长字符串类型

     

    5.导入数据库表

    (1)创建.sql文件

    (2)先产生一个库如auction.c:mysqlbin>mysqladmin -u root -p creat auction,会提示输入密码,然后成功创建。

    (2)导入auction.sql文件

    c:mysqlbin>mysql -u root -p auction < auction.sql。

    通过以上操作,就可以创建了一个数据库auction以及其中的一个表auction。

    6.修改数据库

    (1)在mysql的表中增加字段:

    alter table dbname add column userid int(11) not null primary key auto_increment;

    这样,就在表dbname中添加了一个字段userid,类型为int(11)。

    7.mysql数据库的授权

    mysql>grant select,insert,delete,create,drop

    on *.* (或test.*/user.*/..)

    to 用户名@localhost

    identified by ‘密码’;

    如:新建一个用户帐号以便可以访问数据库,需要进行如下操作:

    mysql> grant usage

    -> ON test.*

    -> TO testuser@localhost;

    Query OK, 0 rows affected (0.15 sec)

    此后就创建了一个新用户叫:testuser,这个用户只能从localhost连接到数据库并可以连接到test 数据库。下一步,我们必须指定testuser这个用户可以执行哪些操作:

    mysql> GRANT select, insert, delete,update

    -> ON test.*

    -> TO testuser@localhost;

    Query OK, 0 rows affected (0.00 sec)

    此操作使testuser能够在每一个test数据库中的表执行SELECT,INSERT和DELETE以及UPDATE查询操作。现在我们结束操作并退出MySQL客户程序:

    mysql> exit

    Bye9!

     

    1:使用SHOW语句找出在服务器上当前存在什么数据库:

    mysql> SHOW DATABASES;

    2:2、创建一个数据库MYSQLDATA

    mysql> Create DATABASE MYSQLDATA;

    3:选择你所创建的数据库

    mysql> USE MYSQLDATA; (按回车键出现Database changed 时说明操作成功!)

    4:查看现在的数据库中存在什么表

    mysql> SHOW TABLES;

    5:创建一个数据库表

    mysql> Create TABLE MYTABLE (name VARCHAR(20), sex CHAR(1));

    6:显示表的结构:

    mysql> DESCRIBE MYTABLE;

    7:往表中加入记录

    mysql> insert into MYTABLE values (“hyq”,”M”);

    8:用文本方式将数据装入数据库表中(例如D:/mysql.txt)

    mysql> LOAD DATA LOCAL INFILE “D:/mysql.txt” INTO TABLE MYTABLE;

    9:导入.sql文件命令(例如D:/mysql.sql)

    mysql>use database;

    mysql>source d:/mysql.sql;

    10:删除表

    mysql>drop TABLE MYTABLE;

    11:清空表

    mysql>delete from MYTABLE;

    12:更新表中数据

    mysql>update MYTABLE set sex=”f” where name=’hyq’;

     

    以下是无意中在网络看到的使用MySql的管理心得,

    摘自:http://www1.xjtusky.com/article/htmldata/2004_12/3/57/article_1060_1.html

     

    在windows中MySql以服务形式存在,在使用前应确保此服务已经启动,未启动可用net start mysql命令启动。而Linux中启动时可用“/etc/rc.d/init.d/mysqld start”命令,注意启动者应具有管理员权限。

    刚安装好的MySql包含一个含空密码的root帐户和一个匿名帐户,这是很大的安全隐患,对于一些重要的应用我们应将安全性尽可能提高,在这里应把匿名帐户删除、 root帐户设置密码,可用如下命令进行:

    use mysql;

    delete from User where User=””;

    update User set Password=PASSWORD(‘newpassword’) where User=’root’;

    如果要对用户所用的登录终端进行限制,可以更新User表中相应用户的Host字段,在进行了以上更改后应重新启动数据库服务,此时登录时可用如下类似命令:

    mysql -uroot -p;

    mysql -uroot -pnewpassword;

    mysql mydb -uroot -p;

    mysql mydb -uroot -pnewpassword;

    上面命令参数是常用参数的一部分,详细情况可参考文档。此处的mydb是要登录的数据库的名称。

    在进行开发和实际应用中,用户不应该只用root用户进行连接数据库,虽然使用root用户进行测试时很方便,但会给系统带来重大安全隐患,也不利于管理技术的提高。我们给一个应用中使用的用户赋予最恰当的数据库权限。如一个只进行数据插入的用户不应赋予其删除数据的权限。MySql的用户管理是通过 User表来实现的,添加新用户常用的方法有两个,一是在User表插入相应的数据行,同时设置相应的权限;二是通过GRANT命令创建具有某种权限的用户。其中GRANT的常用用法如下:

    grant all on mydb.* to NewUserName@HostName identified by “password” ;

    grant usage on *.* to NewUserName@HostName identified by “password”;

    grant select,insert,update on mydb.* to NewUserName@HostName identified by “password”;

    grant update,delete on mydb.TestTable to NewUserName@HostName identified by “password”;

    若要给此用户赋予他在相应对象上的权限的管理能力,可在GRANT后面添加WITH GRANT OPTION选项。而对于用插入User表添加的用户,Password字段应用PASSWORD 函数进行更新加密,以防不轨之人窃看密码。对于那些已经不用的用户应给予清除,权限过界的用户应及时回收权限,回收权限可以通过更新User表相应字段,也可以使用REVOKE操作。

    下面给出本人从其它资料(www.cn-java.com)获得的对常用权限的解释:

    全局管理权限:

    FILE: 在MySQL服务器上读写文件。

    PROCESS: 显示或杀死属于其它用户的服务线程。

    RELOAD: 重载访问控制表,刷新日志等。

    SHUTDOWN: 关闭MySQL服务。

    数据库/数据表/数据列权限:

    Alter: 修改已存在的数据表(例如增加/删除列)和索引。

    Create: 建立新的数据库或数据表。

    Delete: 删除表的记录。

    Drop: 删除数据表或数据库。

    INDEX: 建立或删除索引。

    Insert: 增加表的记录。

    Select: 显示/搜索表的记录。

    Update: 修改表中已存在的记录。

    特别的权限:

    ALL: 允许做任何事(和root一样)。

    USAGE: 只允许登录–其它什么也不允许做。

     

    ———————

    MYSQL常用命令

    有很多朋友虽然安装好了mysql但却不知如何使用它。在这篇文章中我们就从连接MYSQL、修改密码、增加用户等方面来学习一些MYSQL的常用命令。

    有很多朋友虽然安装好了mysql但却不知如何使用它。在这篇文章中我们就从连接MYSQL、修改密码、增加用户等方面来学习一些MYSQL的常用命令。

     

    一、连接MYSQL

     

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

     

    1、例1:连接到本机上的MYSQL

     

    首先在打开DOS窗口,然后进入目录 mysqlbin,再键入命令mysql -uroot -p,回车后提示你输密码,如果刚安装好MYSQL,超级用户root是没有密码的,故直接回车即可进入到MYSQL中了,MYSQL的提示符是:mysql>

     

    2、例2:连接到远程主机上的MYSQL

     

    假设远程主机的IP为:110.110.110.110,用户名为root,密码为abcd123。则键入以下命令:

     

    mysql -h110.110.110.110 -uroot -pabcd123

     

    (注:u与root可以不用加空格,其它也一样)

     

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

     

    二、修改密码

     

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

     

    1、例1:给root加个密码ab12。首先在DOS下进入目录mysqlbin,然后键入以下命令

     

    mysqladmin -uroot -password ab12

     

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

     

    2、例2:再将root的密码改为djg345

     

    mysqladmin -uroot -pab12 password djg345

     

    MYSQL常用命令(下)

    一、操作技巧

     

    1、如果你打命令时,回车后发现忘记加分号,你无须重打一遍命令,只要打个分号回车就可以了。也就是说你可以把一个完整的命令分成几行来打,完后用分号作结束标志就OK。

     

    2、你可以使用光标上下键调出以前的命令。但以前我用过的一个MYSQL旧版本不支持。我现在用的是mysql-3.23.27-beta-win。

     

    二、显示命令

     

    1、显示数据库列表。

     

    show databases;

     

    刚开始时才两个数据库:mysql和test。mysql库很重要它里面有MYSQL的系统信息,我们改密码和新增用户,实际上就是用这个库进行操作。

     

    2、显示库中的数据表:

     

    use mysql; //打开库,学过FOXBASE的一定不会陌生吧

     

    show tables;

     

    3、显示数据表的结构:

     

    describe 表名;

     

    4、建库:

     

    create database 库名;

     

    5、建表:

     

    use 库名;

     

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

     

    6、删库和删表:

     

    drop database 库名;

     

    drop table 表名;

     

    7、将表中记录清空:

     

    delete from 表名;

     

    8、显示表中的记录:

     

    select * from 表名;

     

    三、一个建库和建表以及插入数据的实例

     

    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(10) not null,

    address varchar(50) default ‘深圳’,

    year date

    ); //建表结束

    //以下为插入字段

    insert into teacher values(”,’glchengang’,’深圳一中’,’1976-10-10′);

    insert into teacher values(”,’jack’,’深圳一中’,’1975-12-23′);

     

    注:在建表中(1)将ID设为长度为3的数字字段:int(3)并让它每个记录自动加一:auto_increment并不能为空:not null而且让他成为主字段primary key

    (2)将NAME设为长度为10的字符字段

    (3)将ADDRESS设为长度50的字符字段,而且缺省值为深圳。varchar和char有什么区别呢,只有等以后的文章再说了。

    (4)将YEAR设为日期字段。

     

    如果你在mysql提示符键入上面的命令也可以,但不方便调试。你可以将以上命令原样写入一个文本文件中假设为school.sql,然后复制到c:\下,并在DOS状态进入目录\mysql\bin,然后键入以下命令:

    mysql -uroot -p密码 < c:\school.sql

    如果成功,空出一行无任何显示;如有错误,会有提示。(以上命令已经调试,你只要将//的注释去掉即可使用)。

     

    四、将文本数据转到数据库中

     

    1、文本数据应符合的格式:字段数据之间用tab键隔开,null值用\n来代替.

    例:

    3 rose 深圳二中 1976-10-10

    4 mike 深圳一中 1975-12-23

     

    2、数据传入命令 load data local infile “文件名” into table 表名;

    注意:你最好将文件复制到\mysql\bin目录下,并且要先用use命令打表所在的库 。

     

    五、备份数据库:(命令在DOS的\mysql\bin目录下执行)

     

    mysqldump –opt school>school.bbb

    注释:将数据库school备份到school.bbb文件,school.bbb是一个文本文件,文件名任取,打开看看你会有新发现。

     

    一.SELECT语句的完整语法为:

    SELECT[ALL|DISTINCT|DISTINCTROW|TOP]

    {*|talbe.*|[table.]field1[AS alias1][,[table.]field2[AS alias2][,…]]}

    FROM tableexpression[,…][IN externaldatabase]

    [WHERE…]

    [GROUP BY…]

    [HAVING…]

    [ORDER BY…]

    [WITH OWNERACCESS OPTION]

    说明:

    用中括号([])括起来的部分表示是可选的,用大括号({})括起来的部分是表示必须从中选择其中的一个。

    1 FROM子句

    FROM 子句指定了SELECT语句中字段的来源。FROM子句后面是包含一个或多个的表达式(由逗号分开),其中的表达式可为单一表名称、已保存的查询或由 INNER JOIN、LEFT JOIN 或 RIGHT JOIN 得到的复合结果。如果表或查询存储在外部数据库,在IN 子句之后指明其完整路径。

    例:下列SQL语句返回所有有定单的客户:

    SELECT OrderID,Customer.customerID

    FROM Orders Customers

    WHERE Orders.CustomerID=Customers.CustomeersID

     

    2 ALL、DISTINCT、DISTINCTROW、TOP谓词

    (1) ALL 返回满足SQL语句条件的所有记录。如果没有指明这个谓词,默认为ALL。

    例:SELECT ALL FirstName,LastName

    FROM Employees

    (2) DISTINCT 如果有多个记录的选择字段的数据相同,只返回一个。

    (3) DISTINCTROW 如果有重复的记录,只返回一个

    (4) TOP显示查询头尾若干记录。也可返回记录的百分比,这是要用 TOP N PERCENT子句(其中N 表示百分比)

    例:返回5%定货额最大的定单

    SELECT TOP 5 PERCENT*

    FROM [ Order Details]

    ORDER BY UnitPrice*Quantity*(1-Discount) DESC

     

    3 用 AS 子句为字段取别名

    如果想为返回的列取一个新的标题,或者,经过对字段的计算或总结之后,产生了一个新的值,希望把它放到一个新的列里显示,则用AS保留。

    例:返回FirstName字段取别名为NickName

    SELECT FirstName AS NickName ,LastName ,City

    FROM Employees

    例:返回新的一列显示库存价值

    SELECT ProductName ,UnitPrice ,UnitsInStock ,UnitPrice*UnitsInStock AS valueInStock

    FROM Products

     

    二 .WHERE 子句指定查询条件

     

    1 比较运算符

    比较运算符 含义

    = 等于

    > 大于

    < 小于

    >= 大于等于

    <= 小于等于

    <> 不等于

    !> 不大于

    !< 不小于

    例:返回96年1月的定单

    SELECT OrderID, CustomerID, OrderDate

    FROM Orders

    WHERE OrderDate>#1/1/96# AND OrderDate<#1/30/96#

    注意:

    Mcirosoft JET SQL 中,日期用‘#’定界。日期也可以用Datevalue()函数来代替。在比较字符型的数据时,要加上单引号’’,尾空格在比较中被忽略。

    例:

    WHERE OrderDate>#96-1-1#

    也可以表示为:

    WHERE OrderDate>Datevalue(‘1/1/96’)

    使用 NOT 表达式求反。

    例:查看96年1月1日以后的定单

    WHERE Not OrderDate<=#1/1/96#

    2 范围(BETWEEN 和 NOT BETWEEN)

    BETWEEN …AND…运算符指定了要搜索的一个闭区间。

    例:返回96年1月到96年2月的定单。

    WHERE OrderDate Between #1/1/96# And #2/1/96#

    3 列表(IN ,NOT IN)

    IN 运算符用来匹配列表中的任何一个值。IN子句可以代替用OR子句连接的一连串的条件。

    例:要找出住在 London、Paris或Berlin的所有客户

    SELECT CustomerID, CompanyName, ContactName, City

    FROM Customers

    WHERE City In(‘London’,’ Paris’,’ Berlin’)

    4 模式匹配(LIKE)

    LIKE运算符检验一个包含字符串数据的字段值是否匹配一指定模式。

    LIKE运算符里使用的通配符

    通配符 含义

    ? 任何一个单一的字符

    * 任意长度的字符

    # 0~9之间的单一数字

    [字符列表] 在字符列表里的任一值

    [!字符列表] 不在字符列表里的任一值

    – 指定字符范围,两边的值分别为其上下限

    例:返回邮政编码在(171)555-0000到(171)555-9999之间的客户

    SELECT CustomerID ,CompanyName,City,Phone

    FROM Customers

    WHERE Phone Like ‘(171)555-####’

    LIKE运算符的一些样式及含义

    样式 含义 不符合

    LIKE ‘A*’ A后跟任意长度的字符 Bc,c255

    LIKE’5[*]’ 5*5 555

    LIKE’5?5’ 5与5之间有任意一个字符 55,5wer5

    LIKE’5##5’ 5235,5005 5kd5,5346

    LIKE’[a-z]’ a-z间的任意一个字符 5,%

    LIKE’[!0-9]’ 非0-9间的任意一个字符 0,1

    LIKE’[[]’ 1,*

    三 .用ORDER BY子句排序结果

    ORDER子句按一个或多个(最多16个)字段排序查询结果,可以是升序(ASC)也可以是降序(DESC),缺省是升序。ORDER子句通常放在SQL语句的最后。

    ORDER子句中定义了多个字段,则按照字段的先后顺序排序。

    例:

    SELECT ProductName,UnitPrice, UnitInStock

    FROM Products

    ORDER BY UnitInStock DESC , UnitPrice DESC, ProductName

    ORDER BY 子句中可以用字段在选择列表中的位置号代替字段名,可以混合字段名和位置号。

    例:下面的语句产生与上列相同的效果。

    SELECT ProductName,UnitPrice, UnitInStock

    FROM Products

    ORDER BY 1 DESC , 2 DESC,3

    四 .运用连接关系实现多表查询

    例:找出同一个城市中供应商和客户的名字

    SELECT Customers.CompanyName, Suppliers.ComPany.Name

    FROM Customers, Suppliers

    WHERE Customers.City=Suppliers.City

    例:找出产品库存量大于同一种产品的定单的数量的产品和定单

    SELECT ProductName,OrderID, UnitInStock, Quantity

    FROM Products, [Order Deails]

    WHERE Product.productID=[Order Details].ProductID

    AND UnitsInStock>Quantity

    另一种方法是用 Microsof JET SQL 独有的 JNNER JOIN

    语法:

    FROM table1 INNER JOIN table2

    ON table1.field1 comparision table2.field2

    其中comparision 就是前面WHERE子句用到的比较运算符。

    SELECT FirstName,lastName,OrderID,CustomerID,OrderDate

    FROM Employees

    INNER JOIN Orders ON Employees.EmployeeID=Orders.EmployeeID

    注意:

    INNER JOIN不能连接Memo OLE Object Single Double 数据类型字段。

    在一个JOIN语句中连接多个ON子句

    语法:

    SELECT fields

    FROM table1 INNER JOIN table2

    ON table1.field1 compopr table2.field1 AND

    ON table1.field2 compopr table2.field2 OR

    ON table1.field3 compopr table2.field3

    也可以

    SELECT fields

    FROM table1 INNER JOIN

    (table2 INNER JOIN [( ]table3

    [INNER JOER] [( ]tablex[INNER JOIN]

    ON table1.field1 compopr table2.field1

    ON table1.field2 compopr table2.field2

    ON table1.field3 compopr table2.field3

    外部连接返回更多记录,在结果中保留不匹配的记录,不管存不存在满足条件的记录都要返回另一侧的所有记录。

    FROM table [LEFT|RIGHT]JOIN table2

    ON table1.field1comparision table.field2

    用左连接来建立外部连接,在表达式的左边的表会显示其所有的数据

    例:不管有没有定货量,返回所有商品

    SELECT ProductName ,OrderID

    FROM Products

    LEFT JOIN Orders ON Products.PrductsID=Orders.ProductID

    右连接与左连接的差别在于:不管左侧表里有没有匹配的记录,它都从左侧表中返回所有记录。

    例:如果想了解客户的信息,并统计各个地区的客户分布,这时可以用一个右连接,即使某个地区没有客户,也要返回客户信息。

    空值不会相互匹配,可以通过外连接才能测试被连接的某个表的字段是否有空值。

    SELECT *

    FROM talbe1

    LEFT JOIN table2 ON table1.a=table2.c

    1 连接查询中使用Iif函数实现以0值显示空值

    Iif表达式: Iif(IsNull(Amount,0,Amout)

    例:无论定货大于或小于¥50,都要返回一个标志。

    Iif([Amount]>50,?Big order?,?Small order?)

    五. 分组和总结查询结果

    在SQL的语法里,GROUP BY和HAVING子句用来对数据进行汇总。GROUP BY子句指明了按照哪几个字段来分组,而将记录分组后,用HAVING子句过滤这些记录。

    GROUP BY 子句的语法

    SELECT fidldlist

    FROM table

    WHERE criteria

    [GROUP BY groupfieldlist [HAVING groupcriteria]]

    注:Microsoft Jet数据库 Jet 不能对备注或OLE对象字段分组。

    GROUP BY字段中的Null值以备分组但是不能被省略。

    在任何SQL合计函数中不计算Null值。

    GROUP BY子句后最多可以带有十个字段,排序优先级按从左到右的顺序排列。

    例:在‘WA’地区的雇员表中按头衔分组后,找出具有同等头衔的雇员数目大于1人的所有头衔。

    SELECT Title ,Count(Title) as Total

    FROM Employees

    WHERE Region = ‘WA’

    GROUP BY Title

    HAVING Count(Title)>1

    JET SQL 中的聚积函数

    聚集函数 意义

    SUM ( ) 求和

    AVG ( ) 平均值

    COUNT ( ) 表达式中记录的数目

    COUNT (* ) 计算记录的数目

    MAX 最大值

    MIN 最小值

    VAR 方差

    STDEV 标准误差

    FIRST 第一个值

    LAST 最后一个值

    六. 用Parameters声明创建参数查询

    Parameters声明的语法:

    PARAMETERS name datatype[,name datatype[, …]]

    其中name 是参数的标志符,可以通过标志符引用参数.

    Datatype说明参数的数据类型.

    使用时要把PARAMETERS 声明置于任何其他语句之前.

    例:

    PARAMETERS[Low price] Currency,[Beginning date]datatime

    SELECT OrderID ,OrderAmount

    FROM Orders

    WHERE OrderAMount>[low price]

    AND OrderDate>=[Beginning date]

    七. 功能查询

    所谓功能查询,实际上是一种操作查询,它可以对数据库进行快速高效的操作.它以选择查询为目的,挑选出符合条件的数据,再对数据进行批处理.功能查询包括更新查询,删除查询,添加查询,和生成表查询.

    1 更新查询

    UPDATE子句可以同时更改一个或多个表中的数据.它也可以同时更改多个字段的值.

    更新查询语法:

    UPDATE 表名

    SET 新值

    WHERE 准则

    例:英国客户的定货量增加5%,货运量增加3%

    UPDATE OEDERS

    SET OrderAmount = OrderAmount *1.1

    Freight = Freight*1.03

    WHERE ShipCountry = ‘UK’

    2 删除查询

    DELETE子句可以使用户删除大量的过时的或冗于的数据.

    注:删除查询的对象是整个记录.

    DELETE子句的语法:

    DELETE [表名.*]

    FROM 来源表

    WHERE 准则

    例: 要删除所有94年前的定单

    DELETE *

    FROM Orders

    WHERE OrderData<#94-1-1#

    3 追加查询

    INSERT子句可以将一个或一组记录追加到一个或多个表的尾部.

    INTO 子句指定接受新记录的表

    valueS 关键字指定新记录所包含的数据值.

    INSERT 子句的语法:

    INSETR INTO 目的表或查询(字段1,字段2,…)

    valueS(数值1,数值2,…)

    例:增加一个客户

    INSERT INTO Employees(FirstName,LastName,title)

    valueS(‘Harry’,’Washington’,’Trainee’)

    4 生成表查询

    可以一次性地把所有满足条件的记录拷贝到一张新表中.通常制作记录的备份或副本或作为报表的基础.

    SELECT INTO子句用来创建生成表查询语法:

    SELECT 字段1,字段2,…

    INTO 新表[IN 外部数据库]

    FROM 来源数据库

    WHERE 准则

    例:为定单制作一个存档备份

    SELECT *

    INTO OrdersArchive

    FROM Orders

    八. 联合查询

    UNION运算可以把多个查询的结果合并到一个结果集里显示.

    UNION运算的一般语法:

    [表]查询1 UNION [ALL]查询2 UNION …

    例:返回巴西所有供给商和客户的名字和城市

    SELECT CompanyName,City

    FROM Suppliers

    WHERE Country = ‘Brazil’

    UNION

    SELECT CompanyName,City

    FROM Customers

    WHERE Country = ‘Brazil’

    注:

    缺省的情况下,UNION子句不返回重复的记录.如果想显示所有记录,可以加ALL选项

    UNION运算要求查询具有相同数目的字段.但是,字段数据类型不必相同.

    每一个查询参数中可以使用GROUP BY 子句 或 HAVING 子句进行分组.要想以指定的顺序来显示返回的数据,可以在最后一个查询的尾部使用OREER BY子句.

    九. 交叉查询

    交叉查询可以对数据进行总和,平均,计数或其他总和计算法的计算,这些数据通过两种信息进行分组:一个显示在表的左部,另一个显示在表的顶部.

    Microsoft Jet SQL 用TRANSFROM语句创建交叉表查询语法:

    TRANSFORM aggfunction

    SELECT 语句

    GROUP BY 子句

    PIVOT pivotfield[IN(value1 [,value2[,…]]) ]

    Aggfounction指SQL聚积函数,

    SELECT语句选择作为标题的的字段,

    GROUP BY 分组

    说明:

    Pivotfield 在查询结果集中创建列标题时用的字段或表达式,用可选的IN子句限制它的取值.

    value代表创建列标题的固定值.

    例:显示在1996年里每一季度每一位员工所接的定单的数目:

    TRANSFORM Count(OrderID)

    SELECT FirstName&’’&LastName AS FullName

    FROM Employees INNER JOIN Orders

    ON Employees.EmployeeID = Orders.EmployeeID

    WHERE DatePart(“yyyy”,OrderDate)= ‘1996’

    GROUP BY FirstName&’’&LastName

    ORDER BY FirstName&’’&LastName

    POVOT DatePart(“q”,OrderDate)&’季度’

    十 .子查询

    子查询可以理解为 套查询.子查询是一个SELECT语句.

    1 表达式的值与子查询返回的单一值做比较

    语法:

    表达式 comparision [ANY|ALL|SOME](子查询)

    说明:

    ANY 和SOME谓词是同义词,与比较运算符(=,<,>,<>,<=,>=)一起使用.返回一个布尔值True或 False.ANY的意思是,表达式与子查询返回的一系列的值逐一比较,只要其中的一次比较产生True结果,ANY测试的返回 True值(既WHERE子句的结果),对应于该表达式的当前记录将进入主查询的结果中.ALL测试则要求表达式与子查询返回的一系列的值的比较都产生 True结果,才回返回True值.

    例:主查询返回单价比任何一个折扣大于等于25%的产品的单价要高的所有产品

    SELECT * FROM Products

    WHERE UnitPrice>ANY

    (SELECT UnitPrice FROM[Order Details] WHERE Discount>0.25)

     

    2 检查表达式的值是否匹配子查询返回的一组值的某个值

    语法:

    [NOT]IN(子查询)

    例:返回库存价值大于等于1000的产品.

    SELECT ProductName FROM Products

    WHERE ProductID IN

    (SELECT PrdoctID FROM [Order DEtails]

    WHERE UnitPrice*Quantity>= 1000)

     

    3检测子查询是否返回任何记录

    语法:

    [NOT]EXISTS (子查询)

    例:用EXISTS检索英国的客户

    SELECT ComPanyName,ContactName

    FROM Orders

    WHERE EXISTS

    (SELECT *

    FROM Customers

    WHERE Country = ‘UK’ AND

    Customers.CustomerID= Orders.CustomerID)

  • Apache/MySQL/PHP/phpMyAdmin on FreeBSD

    1. Introduction:

    This article describes how to setup Apache, MySQL, PHP and phpMyAdmin on a server running FreeBSD. The article was written for the software versions below but is likely to work on newer versions without too much difficulty.

     2. Software:

    Operating System:        FreeBSD 7.0 for i386      Download

    Apache:                           2.2.8                                Installed from Ports Collection

    MySQL Server:            5.0.51a                             Installed from Ports Collection

    PHP & Extensions:        5.2.5                                Installed from Ports Collection

    phpMyAdmin:              2.11.5                               Installed from Ports Collection

    3. Before you begin:

    This article assumes you have a working install of FreeBSD 6.2 for i386 logged in as root (or another user in the wheel group and you have used “su”) with the ports collection installed. You can use sysinstall, cvsup or portsnap to install the ports distribution if you have not already done so. See point 2 below.

    Update your ports collection (portsnap fetch, portsnap extract.) (See the FreeBSD Handbook Section 4.5.1)

    4. Installing MySQL:

    (1)  Go to the mysql50-server port directory by typing the command:

                     cd /usr/ports/databases/mysql50-server

     (2) Build the port by typing: (This takes AGES – good time for some food.)

    make BUILD_OPTIMIZED=yes BUILD_STATIC=yes

    (3) Install by typing:

                 make install clean

    (4)Open /etc/rc.conf with your favourite text editor and add the line shown below. This will ensure mysql is enabled and starts on boot.

                    mysql_enable=”YES”

     (5)Start mysql manually to avoid having to reboot now by typing:

             /usr/local/etc/rc.d/mysql-server start

     (6)Set a password for the MySQL root user by executing the command, subtituting your own password in place of new-password:

        /usr/local/bin/mysqladmin -uroot password ‘new-password’

      And you’re done! MySQL is installed.

    5.Installing Apache

    (1)Go to the apache22 port directory by typing the command:

    cd /usr/ports/www/apache22

    (2)Build and install the port by typing: (This takes a while, coffee time!)

    make install clean

    Note: You may want to disable the two DAV options if you don’t need them when prompted

    (3)Open /etc/rc.conf with your favourite text editor and add the line shown below. This will ensure apache is enabled and starts on boot.

    apache22_enable=”YES”

    6.Installing PHP

    (1)Go to the php5 port directory by typing the command:

    cd /usr/ports/lang/php5

    (2)Build and install the port by typing: (Just accept the default options, this takes a while, more coffee.)

    make install clean

    Make sure the APACHE (Build Apache module) option is ticked when configuring the build, leaving all other options as default, before selecting OK.

    (3)Go to the php5-extentions meta port directory by typing the command:

    cd /usr/ports/lang/php5-extentions

    (4)Build and install the port by typing: (Just accept the defaults here, phpMyAdmin will install any other extensions required itself)

    make install clean

    (5)Install the php.ini file:

    cp /usr/local/etc/php.ini-dist /usr/local/etc/php.ini

    版本不同,只面的文件可能有所改变

    php.ini-production对应于php.ini-recommended

    php.ini-development对应于php.ini-dist

    php.ini-development 开发用的,php.ini-produciton 生产机用的,如果做站的话,我觉得应该将php.ini-produciton改为php.ini,用php.ini-produciton可能会出现无法支持PHP,修改php.ini中的短标签开关short_open_tag=Off在作怪,改成On就行了

    (6)Edit your Apache configuration file (/usr/local/etc/apache22/httpd.conf) and add the following lines to the end of the file:

    AddType application/x-httpd-php .php

    AddType application/x-httpd-php-source .phps

     Note: You can add additional extenions other than .php (eg .phtml) seperated by spaces.

    Note: The second line is optional, it will show colour highlighted PHP source for .phps files.

    (7)You should also search for the line that reads:

    DirectoryIndex index.html

    and change it to read:

    DirectoryIndex index.php index.html

    Note: You may also add index.phtml or any other default page if you added additional extentions in the previous step.

    (8)Enable language settings by searching for the line:

    #Include etc/apache22/extra/httpd-languages.conf

    and removing the # comment mark so it reads:

    Include etc/apache22/extra/httpd-languages.conf

    (9)Edit the language settings file (/usr/local/etc/apache22/extra/httpd-languages.conf) and add the following line at the end of the file:

    AddDefaultCharset On

    (10)Start Apache using the startup script:

    /usr/local/etc/rc.d/apache22 start

    And you’re done! Apache with PHP is installed.

    安装Zend Optimizer

    cd /usr/ports/devel/ZendOptimizer/

    make install clean

    ===> ZendOptimizer-3.3.0.a cannot install: doesn’t work with PHP version : 5 (Doesn’t support PHP 5).

    *** Error code 1

    Stop in /usr/ports/devel/ZendOptimizer.

    注:如果你用的是FreeBsd8.0版本的可能会出现上面的情况,这里可以使用使用pkg_add命令来安装Zend Optimizer.

    #pkg_add -r ZendOptimizer

    #rehash

    执行结果将类似如下:

    Fetching ftp://ftp.freebsd.org/pub/FreeBSD/ports/i386/packages-8.0-release/Latest/ZendOptimizer.tbz… Done.

    pkg_add: warning: package ‘ZendOptimizer-3.3.0.a’ requires ‘libxml2-2.7.5’, but ‘libxml2-2.7.7’ is installed

    pkg_add: warning: package ‘ZendOptimizer-3.3.0.a’ requires ‘php5-5.2.11’, but ‘php5-5.3.2’ is installed

     

    ********************************************************************************

     

    You have installed the ZendOptimizer package.

     

    Edit /usr/local/etc/php.ini and add:

     

    [Zend]

    zend_optimizer.optimization_level=15

    zend_extension_manager.optimizer=”/usr/local/lib/php/20060613/Optimizer”

    zend_extension_manager.optimizer_ts=”/usr/local/lib/php/20060613/Optimizer_TS”

    zend_extension=”/usr/local/lib/php/20060613/ZendExtensionManager.so”

    zend_extension_ts=”/usr/local/lib/php/20060613/ZendExtensionManager_TS.so”

     

    NOTE: PHP should be compiled in non-debug mode (default).

     

    ********************************************************************************

    虽然居然成功了,但也可能用phpinfo时候还是不行的![可惜最后还是不行,得到的教训是,不要用太新的版本,这样资料和环境的支持会很不完善。]

     

    7.Installing phpMyAdmin

    (1)Got to the phpmyadmin port directory by typing the command:

    cd /usr/ports/databases/phpmyadmin

    (2)Build and install the port by typing: (Just accept the default options)

    make install clean

    (3)phpMyAdmin is now installed in /usr/local/www/phpMyAdmin. To use it we need to create Alias and Directory entries in /usr/local/etc/apache22/httpd.conf. To do this, add the following lines to the <IfModule alias_module> section (just search for where all the other Alias commands are.)

    Alias /phpmyadmin /usr/local/www/phpMyAdmin

    (4)As /usr/local/www/phpMyadmin is outside of the Apache <DocumentRoot> you will have to make a <Directory> entry for it too. Add the following lines to the end of the <Directory> section: (just search for </Directory>)

    <Directory “/usr/local/www/phpMyAdmin”>

    Order allow,deny

    Allow from all

    </Directory>

     Note:You may prefer to put the Alias entry inside a <VirtualHost> entry if you are hosting multiple sites using name based virtual hosting and do not wish to enable phpMyAdmin on all the sites.

    (5)Create a config directory for phpMyAdmin and make it globally read/write/executable by typing the commands:

    cd /usr/local/www/phpMyAdmin

    mkdir config

    chmod 777 config

    (6)Restart Apache so that the Alias and Directory entries take effect by typing:

    /usr/local/etc/rc.d/apache22 restart

    (7)Configure phpMyAdmin by going to http://hostname/phpmyadmin/scripts/setup.php in your browser and set at least the following:

    • Add Server
      • Change the “Authentication type” dropdown to http to have phpMyAdmin prompt you for a username and password.
      • Delete root from the “User for config” auth textbox so it is blank.
      • You can leave all other settings as they are (even if they are blank.)
      • Click the “Add” button to add the new server

    Save the configuration using the Save button in the Configuration section.

    (8)For the changes to take effect you must copy the generated config file from the phpMyAdmin/config directory to the phpMyAdmin directory by typing the following command: (Note the space dot at the end of the command)

    cp config/config.inc.php .

    (9)You can now delete the config directory you created earlier and reset the permissions on the config.inc.php file to read only typing the commands:

    rm -rf config

    chmod 444 config.inc.php

    (10)That’s it! You can place your web site in /usr/local/www/data/ and access phpMyAdmin at http://hostname/phpmyadmin/ in your web browser and logging in using username root and the MySQL password you set earlier.

    以上安装完,可能有所出入,特别是Apache22可能无法启动,以下两点是一些总结:

    1:注意:apache22有个bug,不能启动FreeBSD自带的一个基于http端口过滤的模块。这个模块的作用很不错——检查HTTP请求是否完整,符合规则accpt一个Http进程,否则就扔掉。你会遇到如下提示

    [Sat Jan 23 22:47:29 2010] [warn] (2)No such file or directory: Failed to enable the ‘httpready’ Accept Filter    解决方法是:

    #kldload accf_http  或者将/boot/defaults/loader.conf==> accf_httpd_load=”YES”

    2.apache22无法启动时,进入/var/logo查看httpd_error.log, 如果出现以下提示:

    [alert] (EAI 8)hostname nor servname provided, or not known: mod_unique_id: unable to find IPv4 address of “shao  Configuration Failed

    解决方法:进入/usr/local/etc/apache22    ee ./httpd.conf

    将LoadModule unique_id_module libexec/apache2/mod_unique_id.so注释掉

    然后启动/usr/local/etc/rc.d/apache22  start即可.

    一个IP多个域名添加方法

    在httpd.conf中去掉httpd-vhosts.conf那一栏注释,然后进入/usr/local/etc/apache22/extra/修改httpd-vhosts.conf网站域名对应的目录,还要加

    <Directory “/usr/home/www/jpeps.com”>

    Options FollowSymLinks

    AllowOverride None

    Order allow,deny

    Allow from all

    </Directory>

    <IfModule dir_module>

    DirectoryIndex index.html index.htm index.php

    </IfModule>

    添加php.ini 被禁用的函数(disable_functions)

    passthru,exec,system,chroot,scandir,chgrp,chown,shell_exec,proc_open,proc_get_status,ini_alter,ini_restore,dl,pfsockopen,openlog,syslog,readlink,symlink,popepassthru,stream_socket_server,fsocket,fsockopen

  • Freebsd9.0安装Nginx+PHP-FPM+MySQL+eAccelerator+Memcached+phpMyAdmin

    更新 ports

    第一种方式: portsnap (自带)

    首先修改/etc/portsnap.conf

    SERVERNAME=portsnap.cn.freebsd.org

    1.下载压缩的 Ports 套件快照到 /var/db/portsnap

    # portsnap fetch

    2.假如是首次运行 Portsnap, 则需要将快照释放到 /usr/ports:

    # portsnap extract

    如果您已经有装好的 /usr/ports 而只想更新, 则应执行下面的命令:

    # portsnap update

    完成后需要退出终端重新登陆。

    复制cvsup更新配置文件

    # cp /usr/share/examples/cvsup/ports-supfile /etc/supfile

    下面是我使用的配置,屏蔽了desktop等一些服务器用不到的软件包,源已经改成中国镜像,速度比国外的主服务器要快很多

    # $FreeBSD: release/9.0.0/share/examples/cvsup/ports-supfile 219858 2011-03-22 04:31:35Z glebius $

    #

    # This file contains all of the “CVSup collections” that make up the

    # FreeBSD-current ports collection.

    #

    # CVSup (CVS Update Protocol) allows you to download the latest CVS

    # tree (or any branch of development therefrom) to your system easily

    # and efficiently (far more so than with sup, which CVSup is aimed

    # at replacing). If you’re running CVSup interactively, and are

    # currently using an X display server, you should run CVSup as follows

    # to keep your CVS tree up-to-date:

    #

    # cvsup ports-supfile

    #

    # If not running X, or invoking cvsup from a non-interactive script, then

    # run it as follows:

    #

    # cvsup -g -L 2 ports-supfile

    #

    # You may wish to change some of the settings in this file to better

    # suit your system:

    #

    # host=CHANGE_THIS.FreeBSD.org

    # This specifies the server host which will supply the

    # file updates. You must change it to one of the CVSup

    # mirror sites listed in the FreeBSD Handbook at

    # http://www.freebsd.org/doc/handbook/cvsup.html#CVSUP-MIRRORS.

    # You can override this setting on the command line

    # with cvsup’s “-h host” option.

    #

    # base=/var/db

    # This specifies the root where CVSup will store information

    # about the collections you have transferred to your system.

    # A setting of “/var/db” will generate this information in

    # /var/db/sup. You can override the “base” setting on the

    # command line with cvsup’s “-b base” option. This directory

    # must exist in order to run CVSup.

    #

    # prefix=/usr

    # This specifies where to place the requested files. A

    # setting of “/usr” will place all of the files requested

    # in “/usr/ports” (e.g., “/usr/ports/devel”, “/usr/ports/lang”).

    # The prefix directory must exist in order to run CVSup.

    # Defaults that apply to all the collections

    #

    # IMPORTANT: Change the next line to use one of the CVSup mirror sites

    # listed at http://www.freebsd.org/doc/handbook/cvsup.html#CVSUP-MIRRORS.

    *default host=cvsup.cn.FreeBSD.org

    *default base=/var/db

    *default prefix=/usr

    *default release=cvs tag=.

    *default delete use-rel-suffix

    # If you seem to be limited by CPU rather than network or disk bandwidth, try

    # commenting out the following line. (Normally, today’s CPUs are fast enough

    # that you want to run compression.)

    *default compress

    ## Ports Collection.

    #

    # The easiest way to get the ports tree is to use the “ports-all”

    # mega-collection. It includes all of the individual “ports-*”

    # collections,

    #ports-all

    # These are the individual collections that make up “ports-all”. If you

    # use these, be sure to comment out “ports-all” above.

    #

    # Be sure to ALWAYS cvsup the ports-base collection if you use any of the

    # other individual collections below. ports-base is a mandatory collection

    # for the ports collection, and your ports may not build correctly if it

    # is not kept up to date.

    ports-base

    #ports-accessibility

    #ports-arabic

    ports-archivers

    #ports-astro

    #ports-audio

    ports-benchmarks

    #ports-biology

    #ports-cad

    #ports-chinese

    #ports-comms

    ports-converters

    ports-databases

    #ports-deskutils

    ports-devel

    ports-dns

    ports-editors

    #ports-emulators

    #ports-finance

    #ports-french

    ports-ftp

    #ports-games

    #ports-german

    #ports-graphics

    #ports-hebrew

    #ports-hungarian

    #ports-irc

    #ports-japanese

    #ports-java

    #ports-korean

    ports-lang

    ports-mail

    ports-math

    ports-misc

    #ports-multimedia

    ports-net

    #ports-net-im

    #ports-net-mgmt

    #ports-net-p2p

    #ports-news

    #ports-palm

    #ports-polish

    #ports-ports-mgmt

    #ports-portuguese

    #ports-print

    #ports-russian

    #ports-science

    ports-security

    ports-shells

    ports-sysutils

    ports-textproc

    #ports-ukrainian

    #ports-vietnamese

    ports-www

    #ports-x11

    #ports-x11-clocks

    #ports-x11-drivers

    #ports-x11-fm

    #ports-x11-fonts

    #ports-x11-servers

    #ports-x11-themes

    #ports-x11-toolkits

    #ports-x11-wm

    然后 更新 Ports到最新

    # cvsup -L 2 -g /etc/supfile

    安装 screen(这个是很有必要,除非你在本地)

    除非你确信在最长可达半天的编译时间里不会因为任何因素掉线,否则尽可能用屏幕保持软件,如果编译一大半突然断线,那就很麻烦了

    # cd /usr/ports/sysutils/screen/

    # make install clean

    options 里直接点 OK 就可以了。编译安装完成后,打入 screen 进入 screen 环境,会有一个提示信息,直接点击回车就好,然后正常进行编译过程。如果断线,可以在重新连上 SSH 后通过下面的命令回到前面的工作中。

    screen -r

    安装 MySQL

    Ports 里提供了很多版本的 MySQL,这里我选择了 5.5

    # cd /usr/ports/databases/mysql55-server

    # make WITH_CHARSET=gbk WITH_XCHARSET=all BUILD_OPTIMIZED=yes BUILD_STATIC=yes install clean

    即可,慢慢等吧,要花一些时间的。

    如果提示 Error when bootstrapping CMake: Cannot find appropriate Makefile processor on this system. Please specify one using environment variable MAKE.

    安装下cmake即可:

    pkg_add cmake -v -r

    安装完成后,在 /usr/local/share/mysql/ 里有很多预先设置好的 MySQL 配置文件,可以根据自己的需要选择这些预先设置好的文件,或者根据自己的需要,写配置文件。

    # cp /usr/local/share/mysql/my-medium.cnf /usr/local/etc/my.cnf

    # rehash

    # echo mysql_enable=”YES” >> /etc/rc.conf

    # /usr/local/etc/rc.d/mysql-server start

    FreeBSD 下安装 MySQL 后,脚本会自动为其建立用户、用户组 mysql。可以根据自己需要,设置安全策略。

    安装 PHP 版本 5.3 .10

    # cd /usr/ports/lang/php5/

    # make config

    这里我根据自己需要,选择了(图片截取自5.3.9)

    # make install clean

    之后安装 PHP5 的扩展库

    # cd /usr/ports/lang/php5-extensions

    # make config

    在对话框中,选择需要的(编译扩展是最耗时间的,至少2-3小时以上,根据需要能少选就少选!以后可以单个安装)

    [X] BCMATH bc style precision math functions

    [X] BZ2 bzip2 library support

    [ ] CALENDAR calendar conversion support

    [X] CTYPE ctype functions

    [X] CURL CURL support

    [ ] DBA dba support

    [ ] DBASE dBase library support

    [X] DOM DOM support

    [ ] EXIF EXIF support

    [ ] FILEINFO fileinfo support

    [X] FILTER input filter support

    [ ] FRIBIDI FriBidi support

    [X] FTP FTP support

    [X] GD GD library support

    [ ] GETTEXT gettext library support

    [ ] GMP GNU MP support

    [X] HASH HASH Message Digest Framework

    [X] ICONV iconv support

    [ ] IMAP IMAP support

    [ ] INTERBASE Interbase 6 database support (Firebird)

    [X] JSON JavaScript Object Serialization support

    [ ] LDAP OpenLDAP support

    [ ] MBSTRING multibyte string support

    [X] MCRYPT Encryption support

    [X] MHASH Crypto-hashing support

    [ ] MING ming shockwave flash support

    [ ] MSSQL MS-SQL database support

    [X] MYSQL MySQL database support

    [ ] MYSQLI MySQLi database support

    [ ] NCURSES ncurses support (CLI only)

    [ ] ODBC unixODBC support

    [X] OPENSSL OpenSSL support

    [ ] PCNTL pcntl support (CLI only)

    [X] PCRE Perl Compatible Regular Expression support

    [ ] PDF PDFlib support (implies GD)

    [X] PDO PHP Data Objects Interface (PDO)

    [X] PDO_SQLITE PDO sqlite driver

    [X] PDO_MYSQL PDO mysql driver

    [ ] PGSQL PostgreSQL database support

    [X] POSIX POSIX-like functions

    [ ] PSPELL pspell support

    [ ] READLINE readline support (CLI only)

    [ ] RECODE recode support

    [X] SESSION session support

    [ ] SHMOP shmop support

    [X] SIMPLEXML simplexml support

    [ ] SNMP SNMP support

    [X] SOAP SOAP support

    [X] SOCKETS sockets support

    [X] SPL Standard PHP Library

    [X] SQLITE sqlite support

    [ ] SYBASE_CT Sybase database support

    [ ] SYSVMSG System V message support

    [ ] SYSVSEM System V semaphore support

    [ ] SYSVSHM System V shared memory support

    [ ] TIDY TIDY support

    [X] TOKENIZER tokenizer support

    [ ] WDDX WDDX support (implies XML)

    [X] XML XML support

    [X] XMLREADER XMLReader support

    [ ] XMLRPC XMLRPC-EPI support

    [X] XMLWRITER XMLWriter support

    [ ] XSL XSL support (Implies DOM)

    [ ] YAZ YAZ support (ANSI/NISO Z39.50)

    [X] ZIP ZIP support

    [X] ZLIB ZLIB support

    选择完成后,继续

    # make install clean

    经过漫长的等待(估计得一个多小时呢),终于完成了编译。启用 PHP-FPM

    # echo php_fpm_enable=”YES” >> /etc/rc.conf

    # /usr/local/etc/rc.d/php-fpm start

    PHP-FPM 的配置文件,在 FreeBSD 下位于 /usr/local/etc/php-fpm.conf,可以自行更改

    安装 nginx

    nginx 的编译所用的时间相对于前两个东西而言,就快非常多了

    # cd /usr/ports/www/nginx

    # make install clean

    编译选项

    [ ] DEBUG Enable nginx debugging

    [ ] DEBUGLOG Enable debug log (–with-debug)

    [ ] FILE_AIO Enable file aio

    [X] IPV6 Enable IPv6

    [ ] GOOGLE_PERFTOOLS Enable google perftools module

    [X] HTTP_MODULE Enable HTTP module

    [ ] HTTP_ADDITION_MODULE Enable http_addition module

    [X] HTTP_CACHE_MODULE Enable http_cache module

    [ ] HTTP_DAV_MODULE Enable http_webdav module

    [ ] HTTP_FLV_MODULE Enable http_flv module

    [ ] HTTP_GEOIP_MODULE Enable http_geoip module

    [X] HTTP_GZIP_STATIC_MODULE Enable http_gzip_static module

    [ ] HTTP_IMAGE_FILTER_MODULE Enable http_image_filter module

    [ ] HTTP_PERL_MODULE Enable http_perl module

    [ ] HTTP_RANDOM_INDEX_MODULE Enable http_random_index module

    [ ] HTTP_REALIP_MODULE Enable http_realip module

    [X] HTTP_REWRITE_MODULE Enable http_rewrite module

    [ ] HTTP_SECURE_LINK_MODULE Enable http_secure_link module

    [X] HTTP_SSL_MODULE Enable http_ssl module

    [X] HTTP_STATUS_MODULE Enable http_stub_status module

    [ ] HTTP_SUB_MODULE Enable http_sub module

    [ ] HTTP_XSLT_MODULE Enable http_xslt module

    [ ] MAIL_MODULE Enable IMAP4/POP3/SMTP proxy modul

    [ ] MAIL_IMAP_MODULE Enable IMAP4 proxy module

    [ ] MAIL_POP3_MODULE Enable POP3 proxy module

    [ ] MAIL_SMTP_MODULE Enable SMTP proxy module

    [ ] MAIL_SSL_MODULE Enable mail_ssl module

    [X] WWW Enable html sample files

    [ ] CACHE_PURGE_MODULE 3rd party cache_purge module

    [ ] ECHO_MODULE 3rd party echo module

    [ ] HEADERS_MORE_MODULE 3rd party headers_more module

    [ ] HTTP_ACCEPT_LANGUAGE 3rd party accept_language module

    [ ] HTTP_ACCESSKEY_MODULE 3rd party http_accesskey module

    [ ] HTTP_AUTH_PAM_MODULE 3rd party http_auth_pam module

    [ ] HTTP_AUTH_REQ_MODULE 3rd party http_auth_request module

    [ ] HTTP_EVAL_MODULE 3rd party eval module

    [ ] HTTP_FANCYINDEX_MODULE 3rd party http_fancyindex module

    [ ] HTTP_GUNZIP_FILTER 3rd party http_gunzip_filter modul

    [ ] HTTP_MOGILEFS_MODULE 3rd party mogilefs module

    [ ] HTTP_MP4_H264_MODULE 3rd party mp4/h264 module

    [ ] HTTP_NOTICE_MODULE 3rd party notice module

    [ ] HTTP_PUSH_MODULE 3rd party push module

    [ ] HTTP_REDIS_MODULE 3rd party http_redis module

    [ ] HTTP_RESPONSE_MODULE 3rd party http_response module

    [ ] HTTP_UPLOAD_MODULE 3rd party upload module

    [ ] HTTP_UPLOAD_PROGRESS 3rd party uploadprogress module

    [ ] HTTP_UPSTREAM_FAIR 3rd party upstream fair module

    [ ] HTTP_UPSTREAM_HASH 3rd party upstream hash module

    [ ] HTTP_UPSTREAM_KEEPALIVE 3rd party upstream keepalive modul

    [ ] HTTP_ZIP_MODULE 3rd party http_zip module

    [ ] MEMC_MODULE 3rd party memc (memcached) module

    [ ] PASSENGER_MODULE 3rd party passenger module

    [ ] SLOWFS_CACHE_MODULE 3rd party slowfs_cache module

    [ ] SUPERVISORD_MODULE 3rd party supervisord module

    [ ] SYSLOG_SUPPORT 3rd party syslog support

    [ ] UDPLOG_MODULE 3rd party udplog (syslog) module

    编译完成后,启动 nginx

    # echo nginx_enable=”YES” >> /etc/rc.conf

    这里先不急着 start nginx,因为现在还没有对 PHP 的支持。

    # vi /usr/local/etc/nginx/nginx.conf

    将如下段落前的 “#” 删除,并且将 html 更改为 /usr/local/www/nginx

    location ~ \.php$ {

    root /usr/local/www/nginx;

    fastcgi_pass 127.0.0.1:9000;

    fastcgi_index index.php;

    fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;

    include fastcgi_params;

    }

    结束后,编辑 /usr/local/etc/nginx/fastcgi_params,加入

    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

    启动 nginx,看看是否已经对 PHP 了

    # /usr/local/etc/rc.d/nginx start

    # echo “<?php phpinfo() ?>” > /usr/local/www/nginx/info.php

    访问 http://yourdomain/info.php,看到 phpinfo 的页面则证明无误。

    安装 eAcceletrator

    eAcceletrator 可以预编译你的 PHP,这样执行的时候,就会起到加速作用。(下图红色地址部分需要根据自己编译结束后给出的地址修改)

    # cd /usr/ports/www/eaccelerator

    # make install clean

    # echo zend_extension=”/usr/local/lib/php/20060613/eaccelerator.so” >> /usr/local/etc/php.ini

    # mkdir /tmp/eaccelerator

    # chown www /tmp/eaccelerator

    # chmod 0700 /tmp/eaccelerator

    # /usr/local/etc/rc.d/php-fpm restart

    再刷新刚才的 info.php,看看是不是加入了 eAcceletrator 的支持

    安装memcached

    cd /usr/ports/databases/memcached

    make install clean

    cd /usr/ports/databases/pecl-memcache

    make install clean

    echo “memcached_enable=YES” >> /etc/rc.conf

    开启 /usr/local/etc/rc.d/memcached start

    下面附上安装过程中会下载的软件(只供大致参考,一般都需要自己下载,可以配置163的镜像源)

    /usr/ports/distfiles/xcb-proto-1.6.tar.bz2

    /usr/ports/distfiles/varnish-3.0.2.tar.gz

    /usr/ports/distfiles/unzip60.tar.gz

    /usr/ports/distfiles/tcl8.5.11-src.tar.gz

    /usr/ports/distfiles/t1lib-5.1.2.tar.gz

    /usr/ports/distfiles/suhosin-patch-5.3.9-0.9.10.patch.gz

    /usr/ports/distfiles/sqlite-src-3071000.zip

    /usr/ports/distfiles/screen-4.0.3.tar.gz

    /usr/ports/distfiles/repcached-2.3.1-1.4.10.patch.gz

    /usr/ports/distfiles/redis-2.4.4.tar.gz

    /usr/ports/distfiles/php-5.3.9.tar.bz2

    /usr/ports/distfiles/pcre-8.21.tar.bz2

    /usr/ports/distfiles/pcre-8.20.tar.bz2

    /usr/ports/distfiles/openldap-2.4.26.tgz

    /usr/ports/distfiles/nss-3.13.1.with.ckbi.1.88.tar.gz

    /usr/ports/distfiles/nload-0.7.3.tar.gz

    /usr/ports/distfiles/Nginx_upstream_hash-0.3.1.tar.gz

    /usr/ports/distfiles/nginx_upstream_fair-20090923.tar.gz

    /usr/ports/distfiles/nginx-1.0.11.tar.gz

    /usr/ports/distfiles/mysql-5.5.20.tar.gz

    /usr/ports/distfiles/memcached-1.4.10.tar.gz

    /usr/ports/distfiles/make-3.82.tar.bz2

    /usr/ports/distfiles/m4-1.4.16.tar.bz2

    /usr/ports/distfiles/libxcb-1.7.tar.bz2

    /usr/ports/distfiles/libtool-2.4.tar.gz

    /usr/ports/distfiles/libpthread-stubs-0.3.tar.bz2

    /usr/ports/distfiles/libpng-1.4.8.tar.xz

    /usr/ports/distfiles/libpng-1.4.8-apng.patch.gz

    /usr/ports/distfiles/libmcrypt-2.5.8.tar.gz

    /usr/ports/distfiles/libiconv-1.13.1.tar.gz

    /usr/ports/distfiles/libgpg-error-1.10.tar.bz2

    /usr/ports/distfiles/libgcrypt-1.5.0.tar.bz2

    /usr/ports/distfiles/libexecinfo-1.1.tar.bz2

    /usr/ports/distfiles/libevent-1.4.14b-stable.tar.gz

    /usr/ports/distfiles/IO-Tty-1.10.tar.gz

    /usr/ports/distfiles/help2man-1.40.5.tar.gz

    /usr/ports/distfiles/haproxy-1.4.16.tar.gz

    /usr/ports/distfiles/gettext-1.05.tar.gz

    /usr/ports/distfiles/gettext-0.18.1.1.tar.gz

    /usr/ports/distfiles/freetype-2.4.7.tar.bz2

    /usr/ports/distfiles/eaccelerator-0.9.6.1.tar.bz2

    /usr/ports/distfiles/cyrus-sasl-2.1.25.tar.gz

    /usr/ports/distfiles/curl-7.21.3.tar.bz2

    /usr/ports/distfiles/cmake-2.8.7.tar.gz

    /usr/ports/distfiles/check-0.9.8.tar.gz

    /usr/ports/distfiles/automake-1.11.1.tar.bz2

    /usr/ports/distfiles/autoconf-2.68.tar.bz2

    /usr/ports/distfiles/agentzh-headers-more-nginx-module-v0.16-0-gde77fd2.tar.gz

    /usr/ports/distfiles/xorg

    /usr/ports/distfiles/ruby

    /usr/ports/distfiles/python

    /usr/ports/distfiles/PECL

    /usr/ports/distfiles/jpeg8b2

    /usr/ports/distfiles/gnome2

    最后说一下安装phpMyAdmin

    cd /usr/ports/databases/phpmyadmin

    make install clean

    Alias /phpmyadmin /usr/local/www/phpMyAdmin

    修改nginx.conf文件

    vi /usr/local/etc/nginx/nginx.conf

    在主域名下面插入

    location /phpmyadmin/ {

    alias /usr/local/www/nginx/phpMyAdmin/;

    index index.php index.html index.htm;

    }

    Location ~ ^/phpmyadmin/(.*\.php)$ {

    root /usr/local/www/nginx/phpMyAdmin/;

    fastcgi_pass unix:/tmp/php-fpm.sock;

    include fastcgi_params;

    fastcgi_param SCRIPT_FILENAME /usr/local/www/nginx/phpMyAdmin/$1;

    fastcgi_param DOCUMENT_ROOT /usr/local/www/nginx/phpMyAdmin;

    }

    然后

    cd /usr/local/www/phpMyAdmin

    mkdir config

    chmod 777 config

    phpMyAdmin by going to http://hostname/phpmyadmin/setup/index.php in your browser and set at least the following:

    做好了一些基本的设置后

    cp config/config.inc.php .

    rm -rf config

    chmod 444 config.inc.php

    这样就可以访问phpMyAdmin了

    以上参考的网站

    Apache/MySQL/PHP/phpMyAdmin on FreeBSD