β

java jdbc 将mysql表转换成protobuf

luanhailiang 294 阅读
package com.leitingjiandui.leveldb;

import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

import java.sql.Types;

import com.mysql.jdbc.Connection;

/**
 * 将mysql所有表的导成protobuf
 * @author luan
 *
 */
public class MysqlToProto {
    /**
     * @param args
     */
    public static void main(String[] args) {
        try {
        	process();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    /**
     * 将mysql类型转成protobuf
     * @param type
     * @return
     */
    static String translateType(int type){
    	switch(type){
    	case Types.BOOLEAN:
    		return "bool";
    	case Types.INTEGER:
    	case Types.TINYINT:
    		return "int32";
    	case Types.DATE:
    	case Types.BIGINT:
    	case Types.TIMESTAMP:
    		return "int64";
    	case Types.CHAR:
    	case Types.VARCHAR:
    	case Types.LONGVARCHAR:
    		return "string";
    	case Types.BLOB:
    	case Types.LONGVARBINARY:
    		return "bytes";
    	case Types.DECIMAL:
    		return"float";
    	}
    	return null;
    }
    /**
     * 生成proto信息
     * @throws SQLException
     */
    static void process() throws SQLException{
    	//注册驱动
        DriverManager.registerDriver(new com.mysql.jdbc.Driver());
        //连接数据库
        Connection connection = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/navalwarfare_001", "root", "mypassword");
        //获取数据库相关数据
        DatabaseMetaData metaData = connection.getMetaData();
        
        
        StringBuilder build = new StringBuilder();
        build.append("package com.leitingjiandui.proto_msg;\n\n");
        //获取数据库所有表
        ResultSet tables = metaData.getTables(null, null, null, null);
        while(tables.next()){
        	String table_name = tables.getString("TABLE_NAME");
        	build.append(String.format("message %s {\n", table_name));
        	//获取表的所有字段
        	ResultSet columns = metaData.getColumns(null, null, table_name, null);
        	int index = 0;
        	while(columns.next()){
        		index++;
        		String column_name = columns.getString("COLUMN_NAME");
        		
        		int data_type = columns.getInt("DATA_TYPE");
//        		String type_name = columns.getString("TYPE_NAME");
//        		build.append(String.format("%d %s",data_type,type_name));
        		build.append(String.format("	optional %s %s  =%d;\n",translateType(data_type), column_name,index));
        	}
        	build.append("}\n");
        }   	
 
        System.out.println(build.toString());
     
        connection.close();
    }
}
作者:luanhailiang
less is more
原文地址:java jdbc 将mysql表转换成protobuf, 感谢原作者分享。

发表评论