import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 项目中常用的工具类
*
* @author tuozixuan
*
*/
public class CommonUtil
{
/**
* 是否为空,包括null和空格字符串
*
* @param text 文本
* @return boolean 是否为空
*/
public static boolean isEmpty(String text)
{
boolean result = false;
if (text == null || "".equals(text.trim()))
{
result = true;
}
return result;
}
/**
* 是否不为空,包括null和空格字符串
*
* @param text 文本
* @return boolean 是否为空
*/
public static boolean isNotEmpty(String text)
{
return !isEmpty(text);
}
/**
* 如果文本为空或空字符串,则返回0,否则返回本身
*
* @param text 文本
* @return String 处理后的文本
*/
public static String emptyToZero(String text)
{
String localText = text;
if (isEmpty(text))
{
localText = "0";
}
else
{
localText = text.trim();
}
return localText;
}
/**
* 对象是否为空
*
* @param object 对象
* @return boolean 是否为空
*/
public static boolean isEmpty(Object object)
{
boolean result = false;
if (object != null && !"".equals(object.toString()) && !"null".equals(object.toString()))
{
result = true;
}
return result;
}
/**
* 如果对象为空,则返回默认值,否则强制转换为int类型
*
* @param obj 对象
* @param defaultInt 默认值
* @return int int类型的数字
*/
public static int objectToInt(Object obj, int defaultInt)
{
return obj == null ? defaultInt : ((Integer) obj).intValue();
}
/**
* 如果对象为空,则返回默认值,否则强制转换为String类型
*
* @param obj 对象
* @param defaultStr 默认值
* @return String String对象
*/
public static String objectToString(Object obj, String defaultStr)
{
return obj == null ? defaultStr : String.valueOf(obj);
}
/**
* 如果对象为空,则返回默认值,否则强制转换为Date类型
*
* @param obj 对象
* @param defaultDate 默认值
* @return Date Date对象
*/
public static Date objectToDate(Object obj, Date defaultDate)
{
return obj == null ? defaultDate : (Date) obj;
}
/**
* 如果对象为空,则返回默认值,否则强制转换为double类型的数值
*
* @param obj 对象
* @param defaultDouble 默认值
* @return double double数值
*/
public static double objectToDouble(Object obj, double defaultDouble)
{
return obj == null ? defaultDouble : ((Double) obj).doubleValue();
}
/**
* 如果对象为空,则返回默认值,否则强制转换为long类型的数值
*
* @param obj 对象
* @param defaultLong 默认值
* @return long long数值
*/
public static long objectToLong(Object obj, long defaultLong)
{
return obj == null ? defaultLong : ((Long) obj).longValue();
}
/**
* 如果对象为空,则返回默认值,否则强制转换为boolean类型的数值
*
* @param obj 对象
* @param defaultBoolean 默认值
* @return boolean boolean数值
*/
public static boolean objectToBoolean(Object obj, boolean defaultBoolean)
{
return obj == null ? defaultBoolean : ((Boolean) obj).booleanValue();
}
/**
* 把字符串转换为日期对象,如果字符串为空或格式不符转换失败,则返回null<br/>
* 1.如果字符串长度为8,则按照yyyyMMdd格式进行转换<br/>
* 2.如果字符串长度为10,则按照yyyy-MM-dd格式进行转换<br/>
* 3.如果字符串长度为14,则按照yyyyMMddHHmmss格式进行转换<br/>
* 4.如果字符串长度为19,则按照yyyy-MM-dd HH:mm:ss格式进行转换<br/>
*
* @param dateStr 日期时间字符串
* @return Date 日期对象
*/
public static Date stringToDate(String dateStr)
{
if (dateStr == null || "".equals(dateStr.trim()))
{
return null;
}
String formatStr = "";
if (dateStr.length() == 8)
{
formatStr = "yyyyMMdd";
}
else if (dateStr.length() == 10)
{
formatStr = "yyyy-MM-dd";
}
else if (dateStr.length() == 14)
{
formatStr = "yyyyMMddHHmmss";
}
else if (dateStr.length() == 19)
{
formatStr = "yyyy-MM-dd HH:mm:ss";
}
Date date = null;
try
{
date = new SimpleDateFormat(formatStr).parse(dateStr);
}
catch (ParseException e)
{
e.printStackTrace();
}
return date;
}
/**
* 获取指定格式的日期时间字符串
*
* @param date 日期
* @param dateFormat 日期时间格式
* @return String 日期时间字符串
*/
public static String getDateStr(Date date, String dateFormat)
{
SimpleDateFormat format = new SimpleDateFormat(dateFormat);
String dateStr = format.format(date);
return dateStr;
}
/**
* 获取日期字符串,格式为yyyy-MM-dd
*
* @param date 日期对象
* @return String 日期字符串
*/
public static String getDateStr(Date date)
{
return getDateStr(date, "yyyy-MM-dd");
}
/**
* 获取日期数字字符串,格式为yyyyMMdd
*
* @param date 日期对象
* @return String 日期数字字符串
*/
public static String getDateNumStr(Date date)
{
return getDateStr(date, "yyyyMMdd");
}
/**
* 获取日期时间字符串,格式为yyyy-MM-dd HH:mm:ss
*
* @param date 日期对象
* @return String 日期字符串
*/
public static String getDateTimeStr(Date date)
{
return getDateStr(date, "yyyy-MM-dd HH:mm:ss");
}
/**
* 获取日期时间数字字符串,格式为yyyyMMddHHmmss
*
* @param date 日期对象
* @return String 日期字符串
*/
public static String getDateTimeNumStr(Date date)
{
return getDateStr(date, "yyyyMMddHHmmss");
}
/**
* 根据指定日期格式把日期字符串转换为日期对象
*
* @param dateStr 日期字符串
* @param dateFormat 日期格式
* @return Date 日期对象
*/
public static Date getDate(String dateStr, String dateFormat)
{
Date date = null;
try
{
if (!isEmpty(dateStr))
{
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
date = sdf.parse(dateStr);
}
}
catch (Exception e)
{
e.printStackTrace();
}
return date;
}
/**
* 获取当前时间
*
* @return Date 当前时间
*/
public static Date getCurrentDate()
{
Calendar cal = Calendar.getInstance();
Date currentDate = cal.getTime();
return currentDate;
}
/**
* 获取当前日期的字符串yyyy-MM-dd
*
* @return String 当前日期的数字字符串
*/
public static String getCurrentDateStr()
{
Date date = getCurrentDate();
return getDateStr(date, "yyyy-MM-dd");
}
/**
* 获取当前日期的数字字符串
*
* @return String 当前日期的数字字符串
*/
public static String getCurrentDateNumStr()
{
Date date = getCurrentDate();
return getDateStr(date, "yyyyMMdd");
}
/**
* 获取当前日期时间字符串,格式为yyyy-MM-dd HH:mm:ss
*
* @return String 日期时间字符串
*/
public static String getCurrentDateTimeStr()
{
Date date = getCurrentDate();
return getDateStr(date, "yyyy-MM-dd HH:mm:ss");
}
/**
* 获取当前日期时间数字字符串,格式为yyyyMMddHHmmss
*
* @return String 日期时间字符串
*/
public static String getCurrentDateTimeNumStr()
{
Date date = getCurrentDate();
return getDateStr(date, "yyyyMMddHHmmss");
}
/**
* 比较格式为yyyy-MM-dd HH:mm:ss的日期字符串的大小
*
* @param dateTime1 日期时间字符串1
* @param dateTime2 日期时间字符串2
* @return int 0:相等 1:前者大约后者 -1:前者小于后者 -2:发生错误
*/
public static int compareStringDate(String dateTime1, String dateTime2)
{
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
try
{
c1.setTime(df.parse(dateTime1));
c2.setTime(df.parse(dateTime2));
}
catch (ParseException e)
{
return -2;
}
int result = c1.compareTo(c2);
if (result == 0)
{
return 0;
}
return result >= 0 ? 1 : -1;
}
/**
* 是否为数字
*
* @param text 要验证的文本
* @return boolean true-是 false-否
*/
public static boolean isNumber(String text)
{
if (isEmpty(text))
{
return false;
}
String numberStr = "0123456789";
for (int i = 0; i < text.length(); i++)
{
char c = text.charAt(i);
if (numberStr.indexOf(String.valueOf(c)) == -1)
{
return false;
}
}
return true;
}
/**
* 是否符合电子邮件地址格式
*
* @param email 电子邮件地址
* @return boolean true-是 false-否
*/
public static boolean isEmail(String email)
{
boolean isEmail = false;
Pattern p = Pattern.compile("([\\w[.-]]+)(@)([\\w[.-]]+\\.[\\w[.-]]+)");
Matcher m = p.matcher(email);
if (m.matches())
{
isEmail = true;
}
return isEmail;
}
/**
* 是否符合手机号码格式
*
* @param mobile 手机号码
* @return boolean true-是 false-否
*/
public static boolean isMobile(String mobile)
{
boolean isMobile = false;
Pattern p = Pattern.compile("((\\()?(\\+)?(86)?1[3|5|8][0-9]{9}(\\))?$)|((\\()?(\\+)?(86)?01[3|5|8][0-9]{9}(\\))?$)");
Matcher m = p.matcher(mobile);
if (m.matches())
{
isMobile = true;
}
return isMobile;
}
/**
* 电话号码格式简单校验,格式为:数字-数字
*
* @param phone 电话号码
* @return boolean true-是 false-否
*/
public static boolean isPhone(String phone)
{
boolean isPhone = false;
int index = phone.indexOf("-");
if (index > 0 && index != phone.length() - 1)
{
String phoneNum = phone.substring(0, index) + phone.substring(index + 1);
if (isNumber(phoneNum))
{
isPhone = true;
}
}
return isPhone;
}
/**
* 是否为密码,允许大小写字母、数字以及下划线,长度为4-16位
*
* @param pwd 密码
* @return boolean true-是 false-否
*/
public static boolean isPassword(String pwd)
{
boolean ifPwd = false;
Pattern p = Pattern.compile("([A-Za-z0-9_]{4,16})");
Matcher m = p.matcher(pwd);
if (m.matches())
{
ifPwd = true;
}
return ifPwd;
}
/**
* 文本是否都有字母组成
*
* @param text 待验证的文本
* @return boolean true-是 false-否
*/
public static boolean isLetter(String text)
{
if (text != null)
{
Pattern pattern = Pattern.compile("^[a-zA-Z]+$");
Matcher matcher = pattern.matcher(text);
if (matcher.matches())
{
return true;
}
}
return false;
}
/**
* 是否为文字,包括中文字符、英文字母和数字
*
* @param text 待验证的文本
* @return boolean true-是 false-否
*/
public static boolean isWord(String text)
{
boolean isWord = false;
if (text != null)
{
Pattern p = Pattern.compile("([A-Za-z0-9\u4E00-\u9FA5])+");
Matcher m = p.matcher(text);
if (m.matches())
{
isWord = true;
}
}
return isWord;
}
/**
* 字符串是否处于指定长度之间
*
* @param text 文本
* @param minLen 最小长度
* @param maxLen 最大长度
* @return boolean true-是 false-否
*/
public static boolean isLength(String text, int minLen, int maxLen)
{
int length = 0;
if (text != null)
{
length = trueLength(text);
}
boolean result = false;
if (length >= minLen && length <= maxLen)
{
result = true;
}
return result;
}
/**
* 获取文本的真实长度,中文-2 英文-1
*
* @param text 文本
* @return int 文本的真实长度
*/
public static int trueLength(String text)
{
int length = 0;
Pattern p = Pattern.compile("([\u4E00-\u9FA5])");
for (int i = 0; i < text.length(); i++)
{
Matcher m = p.matcher(text.charAt(i) + "");
if (m.matches())
{
length += 2;
}
else
{
length++;
}
}
return length;
}
/**
* 检查是否符合昵称规则,4-24个字符, 支持中英文、数字、下划线;<br/>
*
* @param nickName 昵称
* @return boolean true-符合 false-不符合
*/
public static boolean isNickName(String nickName)
{
int length = trueLength(nickName);
if (length < 4 || length > 24)
{
return false;
}
Pattern p = Pattern.compile("([_A-Za-z0-9\u4E00-\u9FA5]){1,24}");
Matcher m = p.matcher(nickName);
if (!m.matches())
{
return false;
}
return true;
}
/**
* 是否URL地址
*
* @param url URL
* @return boolean true-是 false-否
*/
public static boolean isUrl(String url)
{
return validByRegex("(http://|https://)?([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?", url);
}
/**
* 是否为数字字符串
*
* @param s 字符串
* @return boolean true-是 false-否
*/
public static boolean isNumberic(String s)
{
if (isEmpty(s))
{
return false;
}
boolean rtn = validByRegex("^[-+]{0,1}\\d*\\.{0,1}\\d+$", s);
if (rtn)
{
return true;
}
return validByRegex("^0[x|X][\\da-eA-E]+$", s);
}
/**
* 是否为整数字符串
*
* @param s 字符串
* @return boolean true-是 false-否
*/
public static boolean isInteger(String s)
{
boolean result = validByRegex("^[-+]{0,1}\\d*$", s);
return result;
}
/**
* 是否为邮政编码
*
* @param s 字符串
* @return boolean true-是 false-否
*/
public static boolean isZipCode(String s)
{
boolean result = validByRegex("^[0-9]{6}$", s);
return result;
}
/**
* 是否为QQ号码
*
* @param s 字符串
* @return boolean true-是 false-否
*/
public static boolean isQq(String s)
{
boolean result = validByRegex("^[1-9]\\d{4,9}$", s);
return result;
}
/**
* 是否为指定格式的日期字符串
*
* @param strDate 日期字符串
* @param format 日期格式
* @return boolean true-是 false-否
*/
public static boolean isDate(String strDate, String format)
{
boolean result = false;
try
{
DateFormat df = new SimpleDateFormat(format);
Date d = df.parse(strDate);
String strNewDate = df.format(d);
if (strDate.equals(strNewDate))
{
result = true;
}
}
catch (Exception localException)
{
}
return result;
}
/**
* 检验字符串是否匹配指定的正则表达式
*
* @param regex 正则表达式
* @param input 字符串
* @return boolean true-匹配 false-不匹配
*/
public static boolean validByRegex(String regex, String input)
{
Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
Matcher regexMatcher = p.matcher(input);
return regexMatcher.find();
}
/**
* 数组拼装成 xx,yy,zz
*
* @param array 数组
* @param separator 分隔符
* @return String 字符串
*/
public static <T> String join(T[] array, String separator)
{
StringBuffer str = new StringBuffer();
String newStr = "";
if (array != null && array.length > 0)
{
for (T arr : array)
{
str.append(arr).append(separator);
}
newStr = str.substring(0, str.length() - 1);
}
return newStr;
}
/**
* 列表拼装成 xx,yy,zz类型的字符串
*
* @param list 列表
* @param separator 分隔符
* @return String 字符串
*/
public static <T> String join(List<T> list, String separator)
{
StringBuffer str = new StringBuffer();
String newStr = "";
if (list != null && list.size() > 0)
{
for (T arr : list)
{
str.append(arr).append(separator);
}
newStr = str.substring(0, str.length() - 1);
}
return newStr;
}
/**
* 转换为大写
*
* @param str 字符串
* @return String 大写字符串
*/
public static String upperCase(String str)
{
if (str == null)
{
return null;
}
return str.toUpperCase();
}
/**
* 转换为小写
*
* @param str 字符串
* @return String 小写字符串
*/
public static String lowerCase(String str)
{
if (str == null)
{
return null;
}
return str.toLowerCase();
}
/**
* 字符串是否为null或者由空白字符组成
*
* @param str 字符串
* @return boolean true-是 false-否
*/
public static boolean isBlank(String str)
{
if ((str == null) || str.length() == 0)
{
return true;
}
int strLen = str.length();
for (int i = 0; i < strLen; i++)
{
if (!Character.isWhitespace(str.charAt(i)))
{
return false;
}
}
return true;
}
/**
* 字符串是否不为null并且不都由空白字符组成
*
* @param str 字符串
* @return boolean true-是 false-否
*/
public static boolean isNotBlank(String str)
{
return !isBlank(str);
}
/**
* 提供精确的小数位四舍五入处理
*
* @param v 需要四舍五入的数字
* @param scale 小数点后保留几位
* @return double 四舍五入后的结果
*/
public static double round(double v, int scale)
{
if (scale < 0)
{
throw new IllegalArgumentException("The scale must be a positive integer or zero");
}
BigDecimal b = new BigDecimal(Double.toString(v));
BigDecimal one = new BigDecimal("1");
return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
}
/**
* 提供精确的加法运算
*
* @param v1 被加数
* @param v2 加数
* @return 两个参数的和
*/
public static double add(double v1, double v2)
{
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.add(b2).doubleValue();
}
/**
* 提供精确的减法运算
*
* @param v1 被减数
* @param v2 减数
* @return 两个参数的差
*/
public static double sub(double v1, double v2)
{
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.subtract(b2).doubleValue();
}
/**
* 提供精确的乘法运算
*
* @param v1 被乘数
* @param v2 乘数
* @return 两个参数的积
*/
public static double mul(double v1, double v2)
{
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.multiply(b2).doubleValue();
}
/**
* 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指定的精度,以后的数字四舍五入
*
* @param v1 被除数
* @param v2 除数
* @param scale 表示需要精确到小数点以后几位。
* @return 两个参数的商
*/
public static double div(double v1, double v2, int scale)
{
if (scale < 0)
{
throw new IllegalArgumentException("The scale must be a positive integer or zero");
}
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
}
/**
* 获取有★组成的字符串,如:★★★,如果starCount小于等于0,返回空字符串
*
* @param starCount 星星的数量
* @return String starCount个星星组成的字符串
*/
public static String getStarString(int starCount)
{
String starString = "";
if (starCount > 0)
{
for (int i = 0; i < starCount; i++)
{
starString += "★";
}
}
return starString;
}
/**
* 根据类名获取Class类
*
* @param className 全类名
* @return Class<?> Class类
* @throws ClassNotFoundException
*/
public static Class<?> getClass(String className) throws ClassNotFoundException
{
return Class.forName(className);
}
/**
* 是否存在类名指定的类
*
* @param className 类名
* @return boolean true-存在 false-不存在
*/
public static boolean hasClass(String className)
{
boolean has = true;
try
{
Class.forName(className);
}
catch (ClassNotFoundException e)
{
has = false;
}
return has;
}
/**
* 获取类的构造器
*
* @param c 类
* @param parameterTypes 参数类型
* @return Constructor<?> 构造器
* @throws SecurityException
* @throws NoSuchMethodException
*/
public static Constructor<?> getConstructor(Class<?> c, Class<?>[] parameterTypes) throws SecurityException, NoSuchMethodException
{
return c.getConstructor(parameterTypes);
}
/**
* 根据Class类获取类名
*
* @param c Class类
* @return String 类名
*/
public static String getClassName(Class<?> c)
{
String className = c.getSimpleName();
Class<?>[] interfaces = c.getInterfaces();
if ((!className.startsWith("$")) || (interfaces.length == 0))
{
return className;
}
String[] names = new String[interfaces.length];
for (int i = 0; i < interfaces.length; i++)
{
names[i] = interfaces[i].getSimpleName();
}
return className + "(" + join(names, ",") + ")";
}
/**
* SQL特殊字符转义
*
* @param sql 结构化查询语句
* @return String 转义后的SQL
*/
public static String encodeSQL(String sql)
{
if (sql == null)
{
return "";
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < sql.length(); i++)
{
char c = sql.charAt(i);
switch (c)
{
case '\\':
sb.append("\\\\");
break;
case '\r':
sb.append("\\r");
break;
case '\n':
sb.append("\\n");
break;
case '\t':
sb.append("\\t");
break;
case '\b':
sb.append("\\b");
break;
case '\'':
sb.append("''");
break;
case '"':
sb.append("\\\"");
break;
case '%':
sb.append("\\%");
break;
default:
sb.append(c);
}
}
return sb.toString();
}
/**
* MD5散列不可逆加密算法
*
* @param userName 用户名
* @param password 密码
* @return String 加密后的密码
*/
public static String encryptPassword(String userName, String password)
{
String publicKey1 = "jjejduuhjdjdHDUEHWHd3ehgfidhwh23hHJCRIOI4HDHDHFKHFD3dhdhrg2djsHSDFHFEDJGW";
String publicKey2 = "347djejDETahe3j%3jd*%%2DDE223fdhahfh%^@21hdhfhzhdDFQ3hH7eh32hdE#@sdqhqhde";
String publicKey3 = "wkjd@wjsdj2324shjsQWeh2dsGed/#21ssdEdhawehrcyzhzeje2#@SDajw2D2sjzahd3#dSa";
String str = publicKey1 + userName + publicKey2 + password + publicKey3;
return md5(str).toUpperCase();
}
/**
* 使用UTF-8解码字符串
*
* @param paramValue 参数字符串
* @return String 解码后的字符串
* @throws Exception
*/
public static String decodeUTF8(String str)
{
return decode(str, "utf-8");
}
/**
* 用指定的编码类型对字符串进行解码
*
* @param string 字符串
* @param encodeScheme 编码类型
* @return String 解码后的字符串
*/
public static String decode(String string, String encodeScheme)
{
try
{
return java.net.URLDecoder.decode(string, encodeScheme);
}
catch (UnsupportedEncodingException uee)
{
uee.printStackTrace();
}
return string;
}
/**
* 使用UTF-8编码字符串
*
* @param paramValue 参数字符串
* @return String 编码后的字符串
* @throws Exception
*/
public static String encodeUTF8(String str)
{
return encode(str, "utf-8");
}
/**
* 用指定的编码类型对字符串进行编码
*
* @param string 字符串
* @param encodeScheme 编码类型
* @return String 编码后的字符串
*/
public static String encode(String string, String encodeScheme)
{
try
{
return java.net.URLEncoder.encode(string, encodeScheme);
}
catch (UnsupportedEncodingException uee)
{
uee.printStackTrace();
}
return string;
}
/**
* 数组转换为列表
*
* @param array 数组
* @return List<T> 列表
*/
public static <T> List<T> arrayToList(T[] array)
{
List<T> list = null;
if (array != null)
{
list = new ArrayList<T>();
for (int i = 0; i < array.length; i++)
{
list.add(array[i]);
}
}
return list;
}
/**
* 列表转换为数组
*
* @param list 列表
* @param type Class类型
* @return T[] 数组
*/
@SuppressWarnings("unchecked")
public static <T> T[] listToArray(List<T> list, Class<T> type)
{
T[] array = null;
if (list != null)
{
array = (T[]) Array.newInstance(type, list.size());
for (int i = 0; i < list.size(); i++)
{
array[i] = list.get(i);
}
}
return array;
}
/**
* 把字符串由一种编码转换为另一种编码(如果转换失败,则返回原字符串)
*
* @param str 字符串
* @param from 源编码
* @param to 目标编码
* @return String 编码后的字符串
*/
public static String encodingString(String str, String from, String to)
{
String result = str;
try
{
result = new String(str.getBytes(from), to);
}
catch (Exception e)
{
result = str;
}
return result;
}
/**
* MD5加密字符串
*
* @param str 加密前的字符串
* @return String 加密后的字符串
*/
public static String md5(String str)
{
try
{
MessageDigest alg = MessageDigest.getInstance("MD5");
byte[] b = str.getBytes();
alg.reset();
alg.update(b);
byte[] hash = alg.digest();
String d = "";
for (int i = 0; i < hash.length; i++)
{
int v = hash[i] & 0xFF;
if (v < 16)
{
d += "0";
}
d += Integer.toString(v, 16);
}
return d;
}
catch (NoSuchAlgorithmException e)
{
return null;
}
}
/**
* 关闭数据库连接
*
* @param conn 数据库连接
*/
public static void closeConnection(Connection conn)
{
try
{
if ((conn != null) && (!conn.isClosed()))
{
conn.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
/**
* 关闭Statement对象
*
* @param stmt Statement对象
*/
public static void closeStatement(Statement stmt)
{
try
{
if (stmt != null)
{
stmt.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
/**
* 关闭结果集
*
* @param rs ResultSet对象
*/
public static void closeResultSet(ResultSet rs)
{
try
{
if (rs != null)
{
rs.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
/**
* 安全关闭数据库连接、Statement及结果集对象
*
* @param conn 数据库连接对象
* @param stmt Statement对象
* @param rs 结果集对象
*/
public static void close(Connection conn, Statement stmt, ResultSet rs)
{
closeResultSet(rs);
closeStatement(stmt);
closeConnection(conn);
}
/**
* 回滚数据库事务
*
* @param conn 数据库连接
*/
public static void rollback(Connection conn)
{
try
{
if ((conn != null) && (!conn.isClosed()))
{
conn.rollback();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
/**
* 是否为自动提交
*
* @param conn 数据库连接
* @return boolean true-是 false-否
*/
public static boolean isAutoCommit(Connection conn)
{
try
{
if ((conn != null) && (!conn.isClosed()))
{
return conn.getAutoCommit();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
return false;
}
/**
* Connection对象不为null且未关闭的情况下,设置是否自动提交
*
* @param conn 数据库连接
* @param autoCommit 是否自动提交
*/
public static final void setAutoCommit(Connection conn, boolean autoCommit)
{
try
{
if ((conn != null) && (!conn.isClosed()))
{
conn.setAutoCommit(autoCommit);
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
/**
* 提交数据库事务
*
* @param conn Connection对象
*/
public static void commit(Connection conn)
{
try
{
if ((conn != null) && (!conn.isClosed()))
{
conn.commit();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}