Java连接数据库的综合类class;MSSQL(SQL Server )、Oracle、MySQL、PostgreSQL、SAP、SyBase 各种数据库的JDBC驱动下载及连接

JDBC数据库连接

net.sourceforge.jtds.jdbc.Driver

com.microsoft.sqlserver.jdbc.SQLServerDriver

数 据 库 说 明
MySQL http://www.mysql.com/products/connector/j/ Shipped. But need to download the latest for MySQL 4.1 or higher.
Oracle http://www.oracle.com/technology/software/tech/java/sqlj_jdbc/index.html Included.
SQL Server by jTDS http://sourceforge.net/project/showfiles.php?group_id=33291 Included. Support Microsoft SQL Server (6.5, 7, 2000 and 2005)
Postgres http://jdbc.postgresql.org/download.html Included 7.3 JDBC 3
SAP DB http://www.sapdb.org/sap_db_jdbc.htm Included.
SyBase by jTDS http://jtds.sourceforge.net/ Included. Support Sybase (10, 11, 12)
		driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
		url = "jdbc:sqlserver://" + "192.168.0.20" + // ip
				":" + "1433" + // port
				";DatabaseName=" + "xdl_101";// db name
driver = "net.sourceforge.jtds.jdbc.Driver";
url = "jdbc:jtds:sqlserver://" + "192.168.0.20" + // ip
		":" + "1433" + // port
		";DatabaseName=" + "xdl_101";// db name
username = "dbrwsa";
password = "password";
poolName = "sqlserverpool";

DBUtil dbp = new DBUtil(driver, url, username, password, poolName);
	   dbp.getConnection();
  1. MySQL(http://www.mysql.com) mysql-connector-java-2.0.14-bin.jar ;
    Class.forName( “org.gjt.mm.mysql.Driver” );
    cn = DriverManager.getConnection( “jdbc:mysql://MyDbComputerNameOrIP:3306/myDatabaseName”, sUsr, sPwd );

  2. PostgreSQL(http://www.de.postgresql.org) pgjdbc2.jar ;
    Class.forName( “org.postgresql.Driver” );
    cn = DriverManager.getConnection( “jdbc:postgresql://MyDbComputerNameOrIP/myDatabaseName”, sUsr, sPwd );

  3. Oracle(http://www.oracle.com/ip/deploy/database/oracle9i/) classes12.zip ;
    Class.forName( “oracle.jdbc.driver.OracleDriver” );
    cn = DriverManager.getConnection( “jdbc:oracle:thin:@MyDbComputerNameOrIP:1521:ORCL”, sUsr, sPwd );

  4. Sybase(http://jtds.sourceforge.net) jconn2.jar ;
    Class.forName( “com.sybase.jdbc2.jdbc.SybDriver” );
    cn = DriverManager.getConnection( “jdbc:sybase:Tds:MyDbComputerNameOrIP:2638”, sUsr, sPwd );
    //(Default-Username/Password: “dba”/“sql”)

  5. Microsoft SQLServer(http://jtds.sourceforge.net) ;
    Class.forName( “net.sourceforge.jtds.jdbc.Driver” );
    cn = DriverManager.getConnection( “jdbc:jtds:sqlserver://MyDbComputerNameOrIP:1433/master”, sUsr, sPwd );

  6. Microsoft SQLServer(http://www.microsoft.com) ;
    Class.forName( “com.microsoft.jdbc.sqlserver.SQLServerDriver” );
    cn = DriverManager.getConnection( “jdbc:microsoft:sqlserver://MyDbComputerNameOrIP:1433;databaseName=master”, sUsr, sPwd );

  7. ODBC
    Class.forName( “sun.jdbc.odbc.JdbcOdbcDriver” );
    Connection cn = DriverManager.getConnection( “jdbc:odbc:” + sDsn, sUsr, sPwd );

  8. DB2 Class.forName("com.ibm.db2.jdbc.net.DB2Driver");
    String url=“jdbc:db2://192.9.200.108:6789/SAMPLE”
    cn = DriverManager.getConnection( url, sUsr, sPwd );

  9. access由于access并不是作为一项服务运行,所以url的方法对他不适用。access可以通过odbc,也可以通过服务器映射路径的形式找到.mdb文件,参见 http://rmijdbc.objectweb.org/Access/access.html

Java连接数据库的综合类class

package dbop.sql.dbutil.pool;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbcp.ConnectionFactory;
import org.apache.commons.dbcp.DriverManagerConnectionFactory;
import org.apache.commons.dbcp.PoolableConnectionFactory;
import org.apache.commons.dbcp.PoolingDriver;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.pool.ObjectPool;
import org.apache.commons.pool.impl.GenericObjectPool;

import top.nw109.dbop.date.time.TimeUtils;

/**
 * 连接数据库的综合类。 依赖jar包:commons.dbcp,commons.dbutils,commons.pool包。
 * kj 2017.7.13
 */

public class DBUtil {

	private String driver = null;
	private String url = null;
	private String username = null;
	private String password = null;
	private String poolName = null; // 连接池名称
	private ObjectPool connectionPool = null; // 连接池
	// 对应的定时查询类
	private QueryThread queryThread = null;

	/**
	 * 功能:构造函数
	 * 
	 * @param driver
	 *            驱动全类名,例如:com.mysql.jdbc.Driver。
	 * @param url
	 *            数据库url连接,例如:
	 *  "jdbc:mysql://127.0.0.1:3306/test?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8"
	 * @param userName
	 *            数据库用户名,例如:root
	 * @param password
	 *            数据库密码,例如:abc
	 * @param poolName
	 *            创建的数据库连接池的名称,例如mypool,注意一个web容器此名称不能重复。
	 */
	public DBUtil(String driver, String url, String userName, String password,
			String poolName) {
		this.driver = driver;
		this.url = url;
		this.username = userName;
		this.password = password;
		this.poolName = poolName;
	}

	/**
	 * 执行sql。
	 * 
	 * @param conn
	 *            数据库连接
	 * @param pstm
	 *            PreparedStatement
	 * @return int 执行sql对应的影响行。
	 * @throws SQLException
	 */
	public int execute(Connection conn, PreparedStatement pstm)
			throws SQLException {
		try {
			return pstm.executeUpdate();
		} finally {
			Close(conn);
		}
	}

	/**
	 * 查询sql。
	 * 
	 * @param conn
	 *            连接
	 * @param pstm
	 *            PreparedStatement
	 * @return List> 查询的结果集
	 * @throws SQLException
	 */
	public List<Map<String, Object>> query(Connection conn,
			PreparedStatement pstm) throws SQLException {
		try {
			return resultSetToList(pstm.executeQuery());
		} finally {
			Close(conn);
		}
	}

	/**
	 * 功能:将ResultSet 转为List< Map  >
	 * 
	 * @param rs
	 *            ResultSet 原始数据集
	 * @return List< Map  >
	 * @throws java.sql.SQLException
	 */
	@SuppressWarnings("unchecked")
	private List<Map<String, Object>> resultSetToList(ResultSet rs)
			throws java.sql.SQLException {
		if (rs == null)
			return Collections.EMPTY_LIST;

		ResultSetMetaData md = rs.getMetaData(); // 得到结果集(rs)的结构信息,比如字段数、字段名等
		int columnCount = md.getColumnCount(); // 返回此 ResultSet 对象中的列数
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Map<String, Object> rowData = new HashMap<String, Object>();
		while (rs.next()) {
			rowData = new HashMap<String, Object>(columnCount);
			for (int i = 1; i <= columnCount; i++) {
				rowData.put(md.getColumnName(i), rs.getObject(i));
			}
			list.add(rowData);
		}
		return list;
	}

	/**
	 * 执行不含参数查询sql语句。
	 * 
	 * @param sql
	 *            被执行的sql语句
	 * @return List< Map< String,Object > >
	 * @throws SQLException
	 */
	public List<Map<String, Object>> query(String sql) throws SQLException {
		List<Map<String, Object>> results = null;
		Connection conn = null;
		try {
			conn = getConnection();
			QueryRunner qr = new QueryRunner();
			results = qr.query(conn, sql, new MapListHandler());
		} finally {
			//System.out.println("query complete!");
			Close(conn);
		}
		return results;
	}

	/**
	 * 根据参数查询sql语句
	 * 
	 * @param sql
	 *            sql语句
	 * @param param
	 *            参数
	 * @return List< Map  >
	 * @throws SQLException
	 */
	@SuppressWarnings("deprecation")
	public List<Map<String, Object>> query(String sql, Object param)
			throws SQLException {
		List<Map<String, Object>> results = null;
		Connection conn = null;
		try {
			conn = getConnection();
			QueryRunner qr = new QueryRunner();
			results = (List<Map<String, Object>>) qr.query(conn, sql, param,
					new MapListHandler());
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			Close(conn);
		}
		return results;
	}

	/**
	 * 执行sql语句
	 * 
	 * @param sql
	 *            被执行的sql语句
	 * @return 受影响的行
	 * @throws Exception
	 */
	public int execute(String sql) throws Exception {
		Connection conn = getConnection();
		int rows = 0;
		try {
			QueryRunner qr = new QueryRunner();
			rows = qr.update(conn, sql);
		} finally {
			//System.out.println("execute complete!");
			Close(conn);
		}
		return rows;
	}

	/**
	 * 执行含参数的sql语句
	 * 
	 * @param sql
	 *            被执行的sql语句
	 * @param params
	 *            参数
	 * @return 返回受影响的行
	 * @throws Exception
	 */
	public int execute(String sql, Object[] params) throws Exception {
		Connection conn = getConnection();
		int rows = 0;
		try {
			QueryRunner qr = new QueryRunner();
			rows = qr.update(conn, sql, params);
		} finally {
			Close(conn);
		}
		return rows;
	}

	/**
	 * 关闭连接
	 * 
	 * @param conn
	 * @throws SQLException
	 */
	public void Close(Connection conn) throws SQLException {
		if (conn != null) {
			conn.close();
		}
		// System.out.println("Connection close");
		DbUtils.closeQuietly(conn);
	}

	/**
	 * 启动数据库连接池
	 * 
	 */
	private void StartPool() {
		try {
			Class.forName(driver);
		} catch (ClassNotFoundException e1) {
			e1.printStackTrace();
		}
		if (connectionPool != null) {
			ShutdownPool();
		}
		try {
			connectionPool = new GenericObjectPool(null);
			ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(
					url, username, password);
			PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(
					connectionFactory, connectionPool, null, "SELECT 1", false,
					true);
			Class.forName("org.apache.commons.dbcp.PoolingDriver");
			PoolingDriver driver = (PoolingDriver) DriverManager
					.getDriver("jdbc:apache:commons:dbcp:");
			driver.registerPool(poolName, poolableConnectionFactory.getPool());

		} catch (Exception e) {
			e.printStackTrace();
		}
		// 开启查询程序
		queryThread = new QueryThread(this);
		queryThread.start();
	}

	/**
	 * 关闭连接池
	 */
	private void ShutdownPool() {
		try {
			PoolingDriver driver = (PoolingDriver) DriverManager
					.getDriver("jdbc:apache:commons:dbcp:");
			driver.closePool(poolName);
			// 关闭定时查询
			queryThread.setStartQuery(false);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 得到一个连接
	 * 
	 * @return
	 */
	public synchronized Connection getConnection() {
		Connection conn = null;
		try {
			if (connectionPool == null)
				StartPool();
			conn = DriverManager.getConnection("jdbc:apache:commons:dbcp:"
					+ poolName);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}

	public String getPoolName() {
		return poolName;
	}

	public void setPoolName(String poolName) {
		this.poolName = poolName;
	}
}

/**
 * 当连接池启动后会自动定时查询数据库,防止数据库连接超时。
 * 
 */
class QueryThread extends Thread {

	private DBUtil dbUtil = null;
	// 是否开启查询
	private boolean startQuery = true;

	/**
	 * 功能:对应的数据库连接。
	 * 
	 * @param dbUtil
	 *            数据库连接
	 */
	public QueryThread(DBUtil dbUtil) {
		this.dbUtil = dbUtil;
	}

	public void run() {
		while (true) {
			try {
				if (startQuery) {
					this.dbUtil.query("select 1");
				}
				// System.out.println(startQuery+"  123");
				System.out.println(TimeUtils.getTime() + " "
						+ dbUtil.getPoolName() + " " + startQuery);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					Thread.sleep(120000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public void setStartQuery(boolean startQuery) {
		// System.out.println("startQuery shut:"+startQuery);
		this.startQuery = startQuery;
	}

}

你可能感兴趣的:(数据库,Java,jdbc,数据库)