项目开发过程中,如果针对系统不同版本的表结构没有标记,那么以后的更新会相当麻烦,而且问题不断,为了避免这种问题,我们常需要比较两个不同的库的表结构,找出他们的差别并进行更新,windows 下的软件很多,不过大多都是收费的,以下介绍在Linux下相关的软件:
1、sqlupdate
可以直接比较两个表结构文件,使用如下:
sqlupdate --help
sqlupdate v1.6.6 - Copyright (C) Joel Yliluoma (http://iki.fi/bisqwit/)
Usage:
sqlupdate [options] >changes.sql
(Creates an update script)
Options:
-t tablefile Describes the file containing
the new sql layout. Default: tables.sql
-d database Default: winnie3
-h host Default: localhost
-u user Default: root
-i Use CREATE INDEX instead of ALTER..ADD KEY
-m Add comments explaining the differences
-c Ignore character set differences
-p pass
-r Reverse operation. (new->old)
Example:
./sqlupdate -t etimgr.sql -d etimgr | mysql -uroot
This program does not update a database. It only
produces update scripts (which show the differences).
有点不好的地方在于,他会直接更新数据库,而不是生成需要更新的脚本,这点不好,同时针对一些你定义的表结构文件,他认为不合理的会直接给你更改,比如你定义一个表字段如下:
OrdDate date default NULL,其会更新为OrdDate date default '0000-00-00';
2、SchemaSync
python写的工具,不过仅支持mysql5.0以上版本,由于我们当前数据库为mysql4.0.26版本,只能放弃。
3、mysqldiff
perl写的脚本工具,可从CPAN上下载,个人认为此工具相当好,他会原始的告诉你两个库的不同之处,以及需要更新的脚本,使用如下:
mysqldiff --help
Usage: mysqldiff [ options ] <database1> <database2>
Options:
-?, --help show this help
-A, --apply interactively patch database1 to match database2
-B, --batch-apply non-interactively patch database1 to match database2
-d, --debug[=N] enable debugging [level N, default 1]
-o, --only-both only output changes for tables in both databases
-k, --keep-old-tables don't output DROP TABLE commands
-n, --no-old-defs suppress comments describing old definitions
-t, --table-re=REGEXP restrict comparisons to tables matching REGEXP
-i, --tolerant ignore DEFAULT, AUTO_INCREMENT, COLLATE, and formatting changes
-h, --host=... connect to host
-P, --port=... use this port for connection
-u, --user=... user for login if not current user
-p, --password[=...] password to use when connecting to server
-s, --socket=... socket to use when connecting to server
for <databaseN> only, where N == 1 or 2,
--hostN=... connect to host
--portN=... use this port for connection
--userN=... user for login if not current user
--passwordN[=...] password to use when connecting to server
--socketN=... socket to use when connecting to server
Databases can be either files or database names.
If there is an ambiguity, the file will be preferred;
to prevent this prefix the database argument with `db:'.
mysqldiff -u=root -p=XXXX -h a.b.c.d demo1 demo2 >update.sql
此将会输出以demo2为准,demo1需更新的脚本文件,如下:
ALTER TABLE joybom CHANGE COLUMN Remark Remark char(60) default ''; # was char(150) default ''
ALTER TABLE joybom ADD COLUMN Process char(4) default '';
ALTER TABLE joymarker ADD COLUMN Wastage decimal(4,2) default '0.00';
ALTER TABLE ngmssgbx CHANGE COLUMN MsgCode MsgCode varchar(20) NOT NULL default ''; # was varchar(20) default ''
#后代表其原始的字段定义是什么.