天天看点

JDBC保存EXCEL数据到数据库(1.JDBC操作类)

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 *  JDBC辅助类 
 *  用于构建数据库连接(采用单例模式)
 *  本实例采用sqlserver
 */
public final class JDBCUtilSingle {
	static String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
	static String url = "jdbc:sqlserver://ip:port;DatabaseName=test";
	static String username = "sa";
	static String password = "sa";
	static Connection conn = null;
	private static JDBCUtilSingle instance = null;
	
	private JDBCUtilSingle() {
	}
	
	/**
	 * 获得JDBCUtilSingle实例
	 * @return
	 */
	public static JDBCUtilSingle getInstance(){
		if(instance == null){
			synchronized(JDBCUtilSingle.class){ // 给类加锁 防止线程并发
				if(instance == null){
					instance = new JDBCUtilSingle();
				}
			}
		}
		return instance;
	}

	/**
	 * 静态代码块注册数据库驱动,保证只注册执行一次
	 */
	static{
		try {
			Class.forName(driver);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获得数据库链接
	 * @return
	 */
	public Connection getConnection(){
		try {
			conn = DriverManager.getConnection(url,username,password);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}

	/**
	 * 关闭链接等资源
	 * @param rs
	 * @param st
	 * @param conn
	 */
	public void closeConnection(ResultSet rs, Statement st, Connection conn){
		try {
			if(rs != null){
				rs.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally{
			try{
				if(st != null){
					st.close();
				}
			}catch(Exception e){
				e.printStackTrace();
			}finally{
				try{
					if(conn != null){
						conn.close();
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
	}

}
           

继续阅读