Java对JDBC结果集ResultSet的处理

代码中的Json及JsonList为本人重新创建的类,参考代码时可转为自己常用的相应类
/**
     * 将结果集转化为json对象
     *
     * @param resultSet 操作数据库后的结果集
     * @return json类型的结果集
     * @throws SQLException sql异常
     */
    protected static Json getResultSetByJson(ResultSet resultSet) throws SQLException {
        ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
        int columnCount = resultSetMetaData.getColumnCount();
        Json json = new Json();
        while (resultSet.next()) {
            for (int i = 1; i <= columnCount; i++) {
                String key = resultSetMetaData.getColumnLabel(i);
                String value = resultSet.getString(key);
                json.put(key, value);
            }
        }
        return json;
    }

    /**
     * 将结果集转化为JosnList对象
     *
     * @param resultSet 结果集
     * @return jsonlist类型的结果集
     * @throws SQLException sql异常
     */
    protected static JsonList getResultSetByJsonList(ResultSet resultSet) throws SQLException {
        ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
        int columnCount = resultSetMetaData.getColumnCount();
        JsonList jsonList = new JsonList();
        while (resultSet.next()) {
            Json json = new Json();
            for (int i = 1; i <= columnCount; i++) {
                String key = resultSetMetaData.getColumnLabel(i);
                String value = resultSet.getString(key);
                json.put(key, value);
            }
            jsonList.add(json);
        }
        return jsonList;
    }

    /**
     * 将结果集映射为实体类
     *
     * @param resultSet 结果集
     * @param t         实体
     * @param <T>       泛型
     * @return 实体类型的结果集
     * @throws SQLException              sql异常
     * @throws InvocationTargetException 反射异常
     * @throws IllegalAccessException    反射时访问私有成员权限不足导致的异常
     * @throws NoSuchMethodException     得不到方法异常
     */
    protected static <T> T getResultSetByT(ResultSet resultSet, T t) throws SQLException, InvocationTargetException, IllegalAccessException, NoSuchMethodException {
        //获取method方法
        Method[] methods = t.getClass().getMethods();

        //获取ResultSet列名
        ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
        int columnCount = resultSetMetaData.getColumnCount();
        String[] columnNames = new String[columnCount];
        for (int i = 0; i < columnCount; i++) {
            columnNames[i] = resultSetMetaData.getColumnLabel(i + 1);
        }
        //遍历ResultSet
        while (resultSet.next()) {
            for (int i = 0; i < columnNames.length; i++) {
                //取得set方法
                String setMethodName = "set" + columnNames[i];
                //遍历method方法
                for (int j = 0; j < methods.length; j++) {
                    if (methods[j].getName().equalsIgnoreCase(setMethodName)) {
                        setMethodName = methods[j].getName();
                        Object value = resultSet.getObject(columnNames[i]);

                        //通过set方法赋值到实体
                        try {
                            if (value != null) {
                                //实体字段类型和RsultSet一样时
                                Method method = t.getClass().getMethod(setMethodName, value.getClass());
                                method.invoke(t, value);
                            }
                        } catch (Exception e) {
                            //实体字段类型和ResultSet不一样时,转为String
                            Method method = t.getClass().getMethod(setMethodName, String.class);
                            method.invoke(t, value.toString());
                        }
                    }
                }
            }
        }
        return t;
    }

Java网络编程

package com.net;

import java.io.*;
import java.net.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JavaNet {

	/**
	 * 根据域名获取IP
	 * 
	 * @param realmName 域名
	 * @return IP
	 */
	public static String GetIP(String realmName) {
		InetAddress address;
		try {
			address = InetAddress.getByName(realmName);
		} catch (UnknownHostException e) {
			return null;
		}
		return address.getHostAddress();
	}

	/**
	 * 获取端口是否被占用
	 * 
	 * @param host IP
	 * @param port 端口号
	 * @return 端口的使用状态
	 */
	public static boolean PortIsUsed(String host, int port) {
		try {
			Socket socket = new Socket(host, port);
			return true;
		} catch (UnknownHostException e) {
		} catch (IOException e) {
		}
		return false;
	}

	/**
	 * 获取本机IP
	 * 
	 * @return 本机IP地址
	 * @throws UnknownHostException 异常
	 */
	public static String LocalHostAddress() throws UnknownHostException {
		InetAddress address = InetAddress.getLocalHost();
		return address.getHostAddress();
	}

	/**
	 * 获取本机的主机名
	 * 
	 * @return 主机名
	 * @throws UnknownHostException 异常
	 */
	public static String LocalHostName() throws UnknownHostException {
		InetAddress address = InetAddress.getLocalHost();
		return address.getHostName();
	}

	/**
	 * 获取远程文件大小
	 * 
	 * @param fileLocal 文件路径
	 * @return 文件大小,单位为bytes
	 * @throws IOException 异常
	 */
	public static int getHostFileSize(String fileLocal) throws IOException {
		int size;
		URL url = new URL(fileLocal);
		URLConnection conn = url.openConnection();
		size = conn.getContentLength();
		conn.getInputStream().close();
		return size;
	}

	/**
	 * 获取文件的最后修改日期
	 * 
	 * @param fileLocal 文件路径
	 * @return 最后修改日期
	 * @throws IOException 异常
	 */
	public static Date getFileLastEditDate(String fileLocal) throws IOException {
		URL url = new URL(fileLocal);
		URLConnection conn = url.openConnection();
		conn.setUseCaches(false);
		long timestamp = conn.getLastModified();
		conn.getInputStream().close();
		Date date = new Date(timestamp);
		return date;
	}

	/**
	 * 网页抓取
	 * 
	 * @param local 抓取的路径
	 * @param htmlName html名 可为空
	 * @return 抓取的结果
	 * @throws IOException 异常
	 */
	public static String getHtmlText(String local, String htmlName) throws IOException {
		if (!local.contentEquals("http://"))
			return "local error,like http://www.xxx.com";
		if (htmlName == null)
			htmlName = "data.html";
		URL url = new URL(local);
		BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
		BufferedWriter writer = new BufferedWriter(new FileWriter(htmlName));
		String line;
		StringBuffer stringBuffer = new StringBuffer();
		while ((line = reader.readLine()) != null) {
			stringBuffer.append("\n" + line);
			writer.write(line);
			writer.newLine();
		}
		String result = stringBuffer.toString().replaceFirst("\n", "");
		reader.close();
		writer.close();
		return result;
	}

	/**
	 * 获取相应头信息
	 * 
	 * @param local 请求路径 携带http://
	 * @return 响应头信息
	 * @throws IOException 异常
	 */
	public static Map getHeaders(String local) throws IOException {
		URL url = new URL(local);
		URLConnection conn = url.openConnection();
		Map headers = conn.getHeaderFields();
		return headers;
	}

	/**
	 * 解析URL
	 * 
	 * @param local 请求路径
	 * @return url信息
	 * @throws MalformedURLException 异常
	 */
	public static Map getURLInfo(String local) throws MalformedURLException {
		URL url = new URL(local);
		Map map = new HashMap();
		map.put("url", url.toString());
		// 协议
		map.put("protocol", url.getProtocol());
		// 文件名
		map.put("file", url.getFile());
		// 主机
		map.put("host", url.getHost());
		// 路径
		map.put("path", url.getPath());
		// 端口号
		map.put("port", url.getPort());
		// 默认端口号
		map.put("defaultPort", url.getDefaultPort());
		return map;
	}

}


Java发送邮件

		String to = "收件人邮箱";
		String host = "smtp.163.com";
		String name = "发件人邮箱";
		String pwd = "发件人邮箱密码";
		//获取系统属性
		Properties properties = System.getProperties();
		//设置邮箱服务器
		properties.setProperty("mail.smtp.host", host);
		properties.put("mail.smtp.auth", "true");
		try {
			MailSSLSocketFactory sf = new MailSSLSocketFactory();
			sf.setTrustAllHosts(true);
			properties.put("mail.smtp.ssl.enable", "true");
			properties.put("mail.smtp.ssl.socketFactory", sf);
			//获取Session对象
			Session session = Session.getDefaultInstance(properties, new Authenticator() {
				@Override
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication(name, pwd);
				}
			});
			//创建MimeMessage对象
			MimeMessage message = new MimeMessage(session);
			//设置发件人
			message.setFrom(new InternetAddress(name));
			//设置收件人
			message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
			//设置邮件主题
			message.setSubject("测试标题");
			//设置邮件内容
			message.setText("测试内容");
			//发送消息
			Transport.send(message);
			System.out.println("发送中...");
		} catch (MessagingException mex) {
			mex.printStackTrace();
		} catch (GeneralSecurityException e) {
			e.printStackTrace();
		}
message.setText()该方法用于写入文本,邮件内容可改为其它,如下:
注:替换"message.setText("测试内容");"代码实现
// 1.发送 HTML 消息, 可以插入html标签
         message.setContent("<h1>This is actual message</h1>",
                            "text/html" );

// 2.发送内容携带附件等
// 创建消息部分
         BodyPart messageBodyPart = new MimeBodyPart();
 
         // 消息
         messageBodyPart.setText("This is message body");
        
         // 创建多重消息
         Multipart multipart = new MimeMultipart();
 
         // 设置文本消息部分
         multipart.addBodyPart(messageBodyPart);
 
         // 附件部分
         messageBodyPart = new MimeBodyPart();
         String filename = "file.txt";
         DataSource source = new FileDataSource(filename);
         messageBodyPart.setDataHandler(new DataHandler(source));
         messageBodyPart.setFileName(filename);
         multipart.addBodyPart(messageBodyPart);
 
         // 发送完整消息
         message.setContent(multipart );

SwitchItem

/**
 * 根据下划线字段转驼峰字段
 * 
 * @param item 下划线字段
 * @return 驼峰字段
 */
private String SwitchHump(String item) {
   while (true) {
      if (item.contains("_")) {
         int index = item.indexOf("_");
         String value = item.substring(index + 1, index + 2);
         value = value.toUpperCase();
         item = item.replace(item.substring(index, index + 2), value);
      } else {
         break;
      }
   }
   return item;
}

/**
 * 将驼峰转为下划线
 * 
 * @param item 驼峰字段
 * @return 下划线字段
 */
public String SwitchUnderline(String item) {
   String num = "0123456789";
   String result = "";
   for (int index = 0; index &lt; item.length(); index++) {
      String value = item.substring(index, index + 1);
      if (num.contains(value)) {
         value = "_" + value;
      } else if (Character.isUpperCase(value.charAt(0))) {
         value = "_" + value.toLowerCase();
      }
      result += value;
   }
   return result;
}

Switch

/**
 * 将String转换为数组
 * 
 * @param value 数组格式String字符串
 * @return 数组
 */
public static String[] switchTo(String value) {
   return value.replace("[", "").replace("]", "").replaceAll(" ", "").split(",");
}

/**
 * 遍历数组返回字符串
 * 
 * @param values 数组
 * @return 拼接的字符串
 */
public static String switchToString(String[] values) {
   String result = "";
   if (Util.notEmpty(values)) {
      for (String value : values) {
         result += ",'" + value + "'";
      }
      result = result.replaceFirst(",", "");
   }
   return result;
}

/**
 * 将String集合转化为BigDecimal集合
 * 
 * @param values String集合
 * @return BigDecimal集合
 */
public static List&lt;BigDecimal&gt; switchTo(String[] values) {
   List&lt;BigDecimal&gt; result = new ArrayList&lt;&gt;();
   for (String value : values) {
      if (Util.notEmpty(value)) {
         BigDecimal bigDecimal = new BigDecimal(value);
         result.add(bigDecimal);
      } else {
         result.add(null);
      }
   }
   return result;
}

/**
 * 根据BigDecimal集合获取最大值
 * 
 * @param list BigDecimal集合
 * @return 最大值
 */
public static BigDecimal getMax(List&lt;BigDecimal&gt; list) {
   BigDecimal max = list.get(0);
   for (BigDecimal value : list) {
      if (value.subtract(max).doubleValue() &gt; 0) {
         max = value;
      }
   }
   return max;
}

/**
 * 根据BigDecimal集合获取最小值
 * 
 * @param list BigDecimal集合
 * @return 最小值
 */
public static BigDecimal getMin(List&lt;BigDecimal&gt; list) {
   BigDecimal min = list.get(0);
   for (BigDecimal value : list) {
      if (value.subtract(min).doubleValue() &lt; 0) {
         min = value;
      }
   }
   return min;
}

/**
 * 根据BigDecimal集合获取和 只计算正值
 * 
 * @param list BigDecimal集合
 * @return 集合的和
 */
public static BigDecimal getSum(List&lt;BigDecimal&gt; list) {
   BigDecimal sum = new BigDecimal(0);
   for (BigDecimal value : list) {
      if (value.doubleValue() &gt; 0) {
         sum = sum.add(value);
      }
   }
   return sum;
}

/**
 * 根据开始时间结束时间及报表类型获取具体日期集合
 * 
 * @param from 开始时间
 * @param to 结束时间
 * @param period 报表类型
 * @return 具体日期集合
 */
public static String getTradingDates(int from, int to, String period) {
   String dates = "";
   String[] periods = period.split(",");
   for (String p : periods) {
      for (int i = from; i &lt; to; i++) {
         String date = ExcelUtil.getDateByPeriod(String.valueOf(i), p);
         if (!dates.contains(date)) {
            dates += ",'" + date + "'";
         }
      }
   }
   dates = dates.replaceFirst(",", "");
   return dates;
}

/**
 * 根据其他币种类型及金额转换为人民币
 *
 * @param money 金额
 * @param currency 币种代码
 * @return 人民币金额
 */
public static BigDecimal getRMBByOther(BigDecimal money, String currency) {

   if (money == null || money.toString().contains("-")) {
      return new BigDecimal("0");
   }
   switch (currency) {
      case "RMB":
         return money.setScale(5, BigDecimal.ROUND_HALF_UP);
      case "USD":
         return money.multiply(new BigDecimal(6.617)).setScale(5, BigDecimal.ROUND_HALF_UP);
      case "HKD":
         return money.multiply(new BigDecimal(0.848)).setScale(5, BigDecimal.ROUND_HALF_UP);
      case "EUR":
         return money.multiply(new BigDecimal(7.82)).setScale(5, BigDecimal.ROUND_HALF_UP);
      case "YJP":
         return money.multiply(new BigDecimal(0.0585)).setScale(5, BigDecimal.ROUND_HALF_UP);
      case "KRW":
         return money.multiply(new BigDecimal(0.005855)).setScale(5, BigDecimal.ROUND_HALF_UP);
      case "CAD":
         return money.multiply(new BigDecimal(5.2983)).setScale(5, BigDecimal.ROUND_HALF_UP);
      case "GBP":
         return money.multiply(new BigDecimal(8.7232)).setScale(5, BigDecimal.ROUND_HALF_UP);
      case "AUD":
         return money.multiply(new BigDecimal(5.197)).setScale(5, BigDecimal.ROUND_HALF_UP);
      case "CHF":
         return money.multiply(new BigDecimal(6.7438)).setScale(5, BigDecimal.ROUND_HALF_UP);
      case "SGD":
         return money.multiply(new BigDecimal(4.873)).setScale(5, BigDecimal.ROUND_HALF_UP);
      case "TWD":
         return money.multiply(new BigDecimal(0.2189)).setScale(5, BigDecimal.ROUND_HALF_UP);
   }
   return null;
}

DateUtil

/**
 * 获取当前时间的前 day天的日期
 * 
 * @param day 天数
 * @return 字符串格式的前一天日期
 */
public static Date getBeforeDate(int day) {
   Date date = new Date();
   Calendar calendar = Calendar.getInstance();
   calendar.setTime(date);
   calendar.add(Calendar.DATE, -day);
   return calendar.getTime();
}

/**
 * 获取某日期距离今天的天数
 *
 * @param date 日期
 * @return 天数
 */
public static int getDateToDay(Date date) {
   Date day = new Date();
   Calendar calendar = Calendar.getInstance();
   calendar.setTime(day);
   int newday = calendar.get(Calendar.DAY_OF_YEAR);
   calendar.setTime(date);
   return newday - calendar.get(Calendar.DAY_OF_YEAR);
}

/**
 * 根据date返回字符串日期
 * 
 * @param date 日期
 * @return 字符串类型日期
 */
public static String getStringDate(Date date) {
   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
   return sdf.format(date);
}

/**
 * 根据date和格式化类型转换格式
 * 
 * @param date date
 * @param format 格式化类型
 * @return 格式类型的时间
 */
public static String getStringDate(Date date, String format) {
   SimpleDateFormat sdf = new SimpleDateFormat(format);
   return sdf.format(date);
}

/**
 * date转string
 * 
 * @param date date
 * @return string
 * @throws Exception 转换异常
 */
public static Date getDateByString(String date) throws Exception {
   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
   return sdf.parse(date);
}

/**
 * 判断字符串是否能够转成日期类型
 * 
 * @param date 待检测字符串
 * @return 检测结果
 */
public static boolean getDateByStringExist(String date) {
   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
   try {
      sdf.parse(date);
      return true;
   } catch (ParseException e) {
      return false;
   }
}

/**
 * 判断字符串是否能够转成日期类型
 *
 * @param date 待检测字符串
 * @return 检测结果
 */
public static boolean getDateByStringExist(String date, String format) {
   SimpleDateFormat sdf = new SimpleDateFormat(format);
   try {
      sdf.parse(date);
      return true;
   } catch (ParseException e) {
      return false;
   }
}