DataBase.java 8.4 KB
package com.dao.dbutil;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DataBase {
	// private static String ConnectionFirst = "211.99.137.155";
	//private static String ConnectionSecond = "115.28.25.233:3389";
	// private static String ConnectionSecond = "114.215.157.181";
	// private static String ConnectionSecond =
	// "jksermasterrdspublicip.mysql.rds.aliyuncs.com";
	//正式库数据
	private static String ConnectionSecond = "jksermasterrdsprivateip.mysql.rds.aliyuncs.com";
	private static String DB_URL = "";
	//正式库数据
	private static String dbase = "";
	static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	/**
	 * 数据库连接地址 需根据需要修改数据库的名字和用户名密码
	 * 
	 */
	// private static final String DB_URL_TEST = "jdbc:mysql://"
	// + ConnectionSecond
	// + "/test?user=root&password=root&useUnicode=true&characterEncoding=utf-8";

	
	//测试数据库信息
/*	private static final String DB_URL = "jdbc:mysql://" + ConnectionSecond
			+ "/db_bk_cxwsjh?user=root&password=test&useUnicode=true&characterEncoding=utf-8";
*/
	private static final String DRIVER_NAME = "com.mysql.jdbc.Driver";

	/**
	 * 获得连接
	 * 
	 * @return
	 */
	/*
	 * public static Connection getConnection() { try { Class.forName(DRIVER_NAME);
	 * return DriverManager.getConnection(DB_URL); } catch (Exception e) { throw new
	 * RuntimeException(e); } }
	 */

	public static Connection getConnection(String dbname) {
		try {
			Class.forName(DRIVER_NAME);
			dbase = dbname;
			DB_URL = "jdbc:mysql://" + ConnectionSecond + "/" + dbase
					+ "?user=kingtrolDataWri&password=kingtorlData925W&useUnicode=true&characterEncoding=utf-8";
			return DriverManager.getConnection(DB_URL);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 可用于执行INSERT语句,返回生成的主键,如果表不自动创建主键,程序将抛出Runtime异常
	 * 
	 * @param sql
	 * @return 生成的主键
	 */
	public static int executeInsert(String sql) {
		System.out.printf("DBUtil.executeInsert:%s\n", sql);
		Connection connection = null;
		Statement statement = null;
		try {
			connection = getConnection(dbase);
			statement = connection.createStatement();
			statement.executeUpdate(sql);
			ResultSet rs = statement.getGeneratedKeys();
			if (rs.next()) {
				return rs.getInt(1);
			} else {
				throw new RuntimeException("无法获得自动创建的主键");
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			closeConnection(statement, connection);
		}
	}

	/**
	 * 关闭给定的数据库Statement和连接
	 * 
	 * @param statement
	 *            如果为空则忽略
	 * @param connection
	 *            如果为空则忽略
	 */
	public static void closeConnection(Statement statement, Connection connection) {
		try {
			if (statement != null) {
				statement.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
			// 忽略这个异常
		}
		try {
			if (connection != null) {
				connection.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 忽略这个异常
	}

	/**
	 * 数据库的增删改查 连接的是BUS的数据库
	 * 
	 * @param sql
	 * @return
	 */
	public static boolean executeUpdate(String sql) {
		System.out.printf("DBUtil.executeUpdate:%s\n", sql);
		Connection connection = null;
		Statement statement = null;
		try {
			connection = getConnection(dbase);
			statement = connection.createStatement();
			return statement.execute(sql);
		} catch (Exception e) {
			e.printStackTrace();
			return true;
		} finally {
			closeConnection(statement, connection);
		}
	}

	/**
	 * 给页面显示时间用 必须显示偶数时间 因为偶数时间发布
	 * 
	 * @throws ParseException
	 */
	public String showRightTime(String datetime) throws ParseException {
		String resultdate = "";
		Date datenew = null;
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String[] dateArray = datetime.split(" ");// 2013-08-01 08:00:00
		String[] timeArray = dateArray[1].split(":");
		String[] array = { "01", "03", "05", "07", "09", "11", "13", "15", "17", "19", "21", "23" };
		if (timeArray[0].equals(array[0]) || timeArray[0].equals(array[1]) || timeArray[0].equals(array[2])
				|| timeArray[0].equals(array[3]) || timeArray[0].equals(array[4]) || timeArray[0].equals(array[5])
				|| timeArray[0].equals(array[6]) || timeArray[0].equals(array[7]) || timeArray[0].equals(array[8])
				|| timeArray[0].equals(array[9]) || timeArray[0].equals(array[10]) || timeArray[0].equals(array[11])) {
			datenew = format.parse(datetime);
			long time = datenew.getTime();
			time = time - 60 * 60 * 1000;// 减去一小时
			datenew = new Date(time);
			resultdate = format.format(datenew);
			return resultdate;
		} else
			return datetime;
	}

	/**
	 * jsp 页面循环数据 用函数 返回null和真值
	 */
	public static Object getInfo(Map<?, ?> map, String field) {
		Object info = null;
		if (map == null) {
			return info;
		} else
			info = map.get(field);
		// if( (Double)info == -100.0){
		// return null;
		// }else
		if (info == null)
			info = " ";
		return info;
	}

	/**
	 * 去掉小数多余的0
	 * 
	 * @param n
	 * @return
	 */
	public static String roundtofour(Double n) {
		String f1;
		if (n == null) {
			f1 = "";
		}
		if (n == 0) {
			f1 = "0";
		} else {
			BigDecimal bg = new BigDecimal(n);
			f1 = Double.toString(bg.setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue());
			for (int i = 0; i <= 3; i++) {
				int m = f1.length() - 1;
				if (f1.charAt(m) == 48) {
					f1 = f1.substring(0, m);
				}
			}
			if (f1.charAt(f1.length() - 1) == 46) {
				f1 = f1.substring(0, f1.length() - 1);
			}
		}

		return f1;

	}

	/**
	 * 去掉datetime的.0
	 * 
	 * @param time
	 * @return
	 */
	public static String timechange(String time) {
		String result = null;
		try {
			if (time == null || time.equals("") || time.length() < 19) {
				return time;
			}
			result = df.format(df.parse(time.toString()));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

	public static void main(String[] args) {
		double f = 3.0100;

		System.out.println(roundtofour(f));
	}

	// public static String encodeFileName(HttpServletRequest request,
	// String fileName) throws UnsupportedEncodingException {
	// String agent = request.getHeader("USER-AGENT");
	// if (null != agent
	// && (-1 != agent.indexOf("MSIE") || -1 != agent
	// .indexOf("Trident"))) {
	// return URLEncoder.encode(fileName, "utf-8");
	// } else if (null != agent && -1 != agent.indexOf("Chrome")) {
	// return URLEncoder.encode(fileName, "utf-8");
	// } else if (null != agent && -1 != agent.indexOf("Mozilla")) {
	// return "=?utf-8?B?"
	// + (new String(Base64.encodeBase64(fileName
	// .getBytes("utf-8")))) + "?=";
	// } else {
	// return URLEncoder.encode(fileName, "utf-8");
	// }
	// }
	public static String getPost(HttpServletRequest request) throws IOException {
		StringBuffer json = new StringBuffer();
		InputStream in = request.getInputStream();
		BufferedInputStream buf = new BufferedInputStream(in);
		byte[] buffer = new byte[1024];
		int iRead;
		while ((iRead = buf.read(buffer)) != -1) {
			json.append(new String(buffer, 0, iRead, "UTF-8"));
		}
		String jsonresult = URLDecoder.decode(json.toString(), "utf-8");
		return jsonresult;
	}

	/**
	 * @author zsg 2014年4月29日上午11:37:51
	 * @Title: reponseJson
	 * @Description: TODO(异步请求返回 格式json)
	 * @param json
	 * @param response
	 *            设定文件
	 * @return void 返回类型
	 */
	public static void reponseJson(String json, HttpServletResponse response) {
		try {

			response.getWriter().write(json);
			response.getWriter().close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}