java通过代码给所有表的字段批量加索引

package test;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import com.zxkj.utils.jdbc.DaoUtils;

public class DbIndexTest {
	public static void main(String[] args) throws SQLException{
		List<Map<String, Object>> tables = DaoUtils.queryMapList("SELECT table_name FROM information_schema.tables WHERE table_schema = 'traindb'");
		System.out.println(tables);
		tables.stream().forEach(e->{
			String tableName =e.get("table_name")+"" ;
			System.out.println(tableName);
			try {
				List<Map<String, Object>> columns = DaoUtils.queryMapList(
					   "select "
					+" a.table_schema, "
					+" a.table_name, "
					+" b.table_comment table_comment, "
					+" a.column_name column_name, "
					+" a.column_comment column_comment, "
					+" a.column_type column_type, "
					+" a.column_key column_key from  information_schema.columns a "
					+" join information_schema.TABLES b on a.table_name = b.TABLE_NAME "
					+" where a.table_schema = 'traindb' "
					+" and a.table_name = '"+tableName+"' ");
				
				System.out.println(columns);
				columns.stream().forEach(c->{
					String columnName =c.get("column_name")+"" ;
					System.out.println(columnName);
					
					if("id".equals(columnName)){
						try {
							DaoUtils.updateTable("ALTER TABLE "+tableName+" ADD UNIQUE ( "+columnName+" )");
						} catch (Exception e1) {
							// TODO Auto-generated catch block
							//e1.printStackTrace();
							System.err.println("添加主键索引失败");
						}
					}else{

						try {
							DaoUtils.updateTable("ALTER TABLE "+tableName+" ADD INDEX "+columnName+"( "+columnName+" )");
						} catch (Exception e1) {
							// TODO Auto-generated catch block
							//e1.printStackTrace();
							System.err.println("添加主键索引失败");
						}
					}
				});
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		});
	}

}

你可能感兴趣的:(java,开发语言)