pg转mysql_postgresql转mysql生成数据库脚本

package com.wujh.util.sql;

import java.sql.Connection;

import java.sql.DatabaseMetaData;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import java.util.ArrayList;

import java.util.Collections;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

/**

* postgresql转mysql生成数据库脚本

*

* @author wujianh

*

*/

public class PostgresqlConvertMysql {

private static Map tableMap = Collections

.synchronizedMap(new HashMap());

/**

* 读取配置文件获取连接数据库的数据库名

*

* @return String 数据库名

*/

public static Connection getConnection() {

// 声明Connection对象

Connection con;

// 驱动程序名

String driver = "org.postgresql.Driver";

// URL指向要访问的数据库名mydata

String url = "jdbc:postgresql://192.16.51.172:5432/web";

// MySQL配置时的用户名

String user = "web";

// MySQL配置时的密码

String password = "web";

// 遍历查询结果集

try {

// 加载驱动程序

Class.forName(driver);

// 1.getConnection()方法,连接MySQL数据库!!

con = DriverManager.getConnection(url,user,password);

return con;

} catch (ClassNotFoundException e) {

// 数据库驱动类异常处理

System.out.println("Sorry,can`t find the Driver!");

e.printStackTrace();

} catch (SQLException e) {

// 数据库连接失败异常处理

e.printStackTrace();

} catch (Exception e) {

// TODO: handle exception

e.printStackTrace();

} finally {

// System.out.println("数据库数据成功获取!!");

}

return null;

}

/**

* 获取指定数据库和用户的所有表名

*

* @param conn

* 连接数据库对象

* @param user

* 用户

* @param database

* 数据库名

* @return

*/

public static List getAllTableNames(Connection conn,String user,

String database) {

List tableNames = new ArrayList();

if (conn != null) {

try {

DatabaseMetaData dbmd = conn.getMetaData();

// 表名列表

ResultSet rest = dbmd.getTables(database,null,

new String[] { "TABLE" });

// 输出 table_name

while (rest.next()) {

String tableSchem = rest.getString("TABLE_SCHEM");

if (user.equalsIgnoreCase(tableSchem)) {

tableNames.add(rest.getString("TABLE_NAME"));

}

}

} catch (SQLException e) {

e.printStackTrace();

}

}

return tableNames;

}

public static void main(String[] args) throws SQLException {

Connection conn = getConnection();

Statement statement = conn.createStatement();

/**

* 1.获取表名注释

*/

String tableSql = "SELECT tablename,obj_description(relfilenode,'pg_class') as comment"

+ " FROM pg_tables a,pg_class b"

+ " WHERE a.tablename = b.relname "

+ " and a.tablename NOT LIKE 'pg%' AND a.tablename NOT LIKE 'sql_%' "

+ " ORDER BY a.tablename";

// 用来获取表中所有列的注释

ResultSet tableRs = statement.executeQuery(tableSql);

String tableName = null;

String tableComment = null;

while (tableRs.next()) {

tableName = tableRs.getString("tablename");

tableComment = tableRs.getString("comment") == null ? ""

: tableRs.getString("comment");

if (null == tableName || "".equals(tableName)) {

continue;

}

tableMap.put(tableName,tableComment);

}

tableRs.close();

StringBuffer sb = null;

List tables = getAllTableNames(conn,"public","mcrc_web");

for (String table : tables) {

if (null == table || "".equals(table)) {

continue;

}

/**

* 2.获取主键,存在问题:多个字段组合的主键,只出来一个

*/

String pkSql = "select pg_constraint.conname as pk_name,pg_attribute.attname as colname,pg_type.typname as typename from"

+ " pg_constraint inner join pg_class on pg_constraint.conrelid = pg_class.oid "

+ " inner join pg_attribute on pg_attribute.attrelid = pg_class.oid "

+ " and pg_attribute.attnum = pg_constraint.conkey[1]"

+ " inner join pg_type on pg_type.oid = pg_attribute.atttypid"

+ " where pg_class.relname = '" + table + "' "

+ " and pg_constraint.contype='p'";

// 用来获取表中所有列的注释

ResultSet pkRs = statement.executeQuery(pkSql);

String pkName = null;

while (pkRs.next()) {

pkName = pkRs.getString("colname") == null ? ""

: pkRs.getString("colname");

}

pkRs.close();

/**

* 3.获取表中所有列

*/

String sql = "SELECT col_description(a.attrelid,a.attnum) as comment,format_type(a.atttypid,a.atttypmod) as type,"

+ "a.attname as name,a.attnotnull as notnull "

+ "FROM pg_class as c,pg_attribute as a "

+ "where c.relname = '" + table

+ "' and a.attrelid = c.oid and a.attnum>0";

// 用来获取表中所有列的结果集

ResultSet rs = statement.executeQuery(sql);

sb = new StringBuffer();

sb.append("CREATE TABLE " + table + " (");

sb.append(" \r\n");

String comment = null;

String type = null;

String name = null;

String notnull = null;

while (rs.next()) {

comment = rs.getString("comment") == null ? ""

: rs.getString("comment");

type = rs.getString("type");

name = rs.getString("name");

notnull = rs.getString("notnull");

String nullFlag = null;

if ("t".equalsIgnoreCase(notnull)) {

nullFlag = " DEFAULT NULL COMMENT ";

} else if ("f".equalsIgnoreCase(notnull)) {

nullFlag = " NOT NULL COMMENT ";

}

if ("-".equals(type) && name.contains(".......")) {

continue;

} else if ("character".equalsIgnoreCase(type)) {

sb.append("" + name + " varchar"

+ type.substring(9,type.length()) + nullFlag + "'"

+ comment + "'");

} else if (type.contains("character varying")) {

sb.append("" + name + " varchar"

+ type.substring(17,type.length()) + nullFlag + "'"

+ comment + "'");

} else if (type.contains("timestamp")) {

sb.append("" + name + " datetime " + nullFlag + "'"

+ comment + "'");

} else if ("bigint".equalsIgnoreCase(type)) {

sb.append("" + name + " bigint(20) " + nullFlag + "'"

+ comment + "'");

} else if ("smallint".equalsIgnoreCase(type)) {

sb.append("" + name + " int(10) " + nullFlag + "'" + comment

+ "'");

} else {

sb.append("" + name + " " + type + " " + nullFlag + "'"

+ comment + "'");

}

sb.append(",\r\n");

}

sb.append("PRIMARY KEY (" + pkName + ") \r\n");

sb.append(

") ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='"

+ tableMap.get(table) + "';");

System.out.println(sb.toString() + " \r\n");

rs.close();

}

conn.close();

}

}

/*******************生成结果*N ***********************/

CREATE TABLE z_t_mm_library ( mm_id varchar(10) DEFAULT NULL COMMENT 'Mm编号',mm_code varchar(10) DEFAULT NULL COMMENT 'Mm码',is_source int(10) NOT NULL COMMENT '来源 0:生成 1:再分配',edt_time datetime NOT NULL COMMENT '录入时间',PRIMARY KEY (mm_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='Mm库表信息';

你可能感兴趣的:(pg转mysql)