iis服务器助手广告广告
返回顶部
首页 > 资讯 > 数据库 >JDBC连接数据库实例
  • 1643
分享到

JDBC连接数据库实例

2024-04-02 19:04:59 1643人浏览 薄情痞子
摘要

package javacommon.base; import java.sql.Connection; import java.sql.PreparedStatement;

package javacommon.base;

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



public class JDBCTemplate {	

	private Connection conn = null;
	
	private Connection getConnection() {
         if(conn == null) {
        	 conn = DBManager.getConn();
         }
         return conn;
	}
	
	public JDBCTemplate(Connection conn) {
		this.conn = conn;
	}
	
	public JDBCTemplate() {
		conn = getConnection();
	}	
	
	public Connection getConn() {
        return conn;
    }

    public void beginTranscation() throws SQLException {
		conn.setAutoCommit(false);
	}
	
	public void commit() throws SQLException {
		conn.commit();
	}
	
	@SuppressWarnings("unchecked")
	public List<Map> query(String sql, Object[] params) throws SQLException {
		
		PreparedStatement pStmt = null;
		ResultSet rSet = null;
		List<Map> list = new ArrayList<Map>();
		
		try {
			pStmt = conn.prepareStatement(sql);
			for (int i = 0; i < params.length; i++) {
				pStmt.setObject(i + 1, params[i]);
			}
			rSet = pStmt.executeQuery();
			ResultSetMetaData rsmd = rSet.getMetaData();
			String[] names = new String[rsmd.getColumnCount()];
			for (int i = 0; i < names.length; i++) {
				names[i] = rsmd.getColumnName(i + 1);
			}
			while (rSet.next()) {
				Map row = new HashMap();
				for (int i = 0; i < names.length; i++) {
					row.put(names[i], rSet.getObject(i + 1));
				}
				list.add(row);
			}
		} catch(SQLException e) {
			e.printStackTrace();
			throw e;
		} finally {
			if (rSet != null) {
				try {
					rSet.close();
				} catch(SQLException e) {}
			}
			if (pStmt != null) {
				try {
					pStmt.close();
				} catch(SQLException e) {}
			}
		}
		return list;
	}
	
	
	public int insert(String sql, Object[] params) throws SQLException {
		return executeUpdate(sql, params);
	}
	
	
	public int executeUpdate(String sql, Object[] params) throws SQLException {
		PreparedStatement pStmt = null;
		ResultSet rSet = null;
		int result = 0;
		
		try {
			pStmt = conn.prepareStatement(sql);
			for (int i = 0; i < params.length; i++) {
				pStmt.setObject(i + 1, params[i]);
			}
			result = pStmt.executeUpdate();
		} catch(SQLException e) {
			e.printStackTrace();
			throw e;
		} finally {
			if (pStmt != null) {
				try {
					pStmt.close();
				} catch(SQLException e) {}
			}
		}
		return result;		
	}
	
	public void close() {
		
		if (conn != null) {
			DBManager.closeConn(conn);
		}
		
	}
}
package javacommon.base;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class DBManager {
	private static final Log LOG = LogFactory.getLog(DBManager.class);
	private static DataSource dataSource;
	
	static {
		Properties properties = PropertiesHandler.readPropertiesFile("/opt/hr/hr-info-sync.properites");
		try {
			BasicDataSource basicDataSource = new BasicDataSource();
			if (null != properties
					.getProperty("dataSource.accessToUnderlyinGConnectionAllowed")) {
				basicDataSource
						.setAccessToUnderlyingConnectionAllowed(Boolean.valueOf(properties
								.getProperty("dataSource.accessToUnderlyingConnectionAllowed")));
			}
			// if (null !=
			// properties.getProperty("dataSource.connectionInitSqls"))
			// {basicDataSource.setConnectionInitSqls(properties.getProperty("dataSource.connectionInitSqls"));}
			if (null != properties
					.getProperty("dataSource.connectionProperties")) {
				basicDataSource.setConnectionProperties(properties
						.getProperty("dataSource.connectionProperties"));
			}
			if (null != properties.getProperty("dataSource.defaultAutoCommit")) {
				basicDataSource.setDefaultAutoCommit(Boolean.valueOf(properties
						.getProperty("dataSource.defaultAutoCommit")));
			}
			if (null != properties.getProperty("dataSource.defaultCatalog")) {
				basicDataSource.setDefaultCatalog(properties
						.getProperty("dataSource.defaultCatalog"));
			}
			if (null != properties.getProperty("dataSource.defaultReadOnly")) {
				basicDataSource.setDefaultReadOnly(Boolean.valueOf(properties
						.getProperty("dataSource.defaultReadOnly")));
			}
			if (null != properties
					.getProperty("dataSource.defaultTransactionIsolation")) {
				basicDataSource
						.setDefaultTransactionIsolation(Integer.valueOf(properties
								.getProperty("dataSource.defaultTransactionIsolation")));
			}
			// if (null !=
			// properties.getProperty("dataSource.driverClassLoader"))
			// {basicDataSource.setDriverClassLoader(properties.getProperty("dataSource.driverClassLoader"));}
			if (null != properties.getProperty("dataSource.driverClassName")) {
				basicDataSource.setDriverClassName(properties
						.getProperty("dataSource.driverClassName"));
			}
			if (null != properties.getProperty("dataSource.initialSize")) {
				basicDataSource.setInitialSize(Integer.valueOf(properties
						.getProperty("dataSource.initialSize")));
			}
			if (null != properties.getProperty("dataSource.logAbandoned")) {
				basicDataSource.setLogAbandoned(Boolean.valueOf(properties
						.getProperty("dataSource.logAbandoned")));
			}
			if (null != properties.getProperty("dataSource.loginTimeout")) {
				basicDataSource.setLoginTimeout(Integer.valueOf(properties
						.getProperty("dataSource.loginTimeout")));
			}
			// if (null != properties.getProperty("dataSource.logWriter"))
			// {basicDataSource.setLogWriter(properties.getProperty("dataSource.logWriter"));}
			if (null != properties.getProperty("dataSource.maxActive")) {
				basicDataSource.setMaxActive(Integer.valueOf(properties
						.getProperty("dataSource.maxActive")));
			}
			if (null != properties.getProperty("dataSource.maxIdle")) {
				basicDataSource.setMaxIdle(Integer.valueOf(properties
						.getProperty("dataSource.maxIdle")));
			}
			if (null != properties
					.getProperty("dataSource.maxOpenPreparedStatements")) {
				basicDataSource
						.setMaxOpenPreparedStatements(Integer.valueOf(properties
								.getProperty("dataSource.maxOpenPreparedStatements")));
			}
			if (null != properties.getProperty("dataSource.maxWait")) {
				basicDataSource.setMaxWait(Long.valueOf(properties
						.getProperty("dataSource.maxWait")));
			}
			if (null != properties
					.getProperty("dataSource.minEvictableIdleTimeMillis")) {
				basicDataSource
						.setMinEvictableIdleTimeMillis(Long.valueOf(properties
								.getProperty("dataSource.minEvictableIdleTimeMillis")));
			}
			if (null != properties.getProperty("dataSource.minIdle")) {
				basicDataSource.setMinIdle(Integer.valueOf(properties
						.getProperty("dataSource.minIdle")));
			}
			if (null != properties
					.getProperty("dataSource.numTestsPerEvictionRun")) {
				basicDataSource
						.setNumTestsPerEvictionRun(Integer.valueOf(properties
								.getProperty("dataSource.numTestsPerEvictionRun")));
			}
			if (null != properties.getProperty("dataSource.passWord")) {
				basicDataSource.setPassword(properties
						.getProperty("dataSource.password"));
			}
			if (null != properties
					.getProperty("dataSource.poolPreparedStatements")) {
				basicDataSource
						.setPoolPreparedStatements(Boolean.valueOf(properties
								.getProperty("dataSource.poolPreparedStatements")));
			}
			if (null != properties.getProperty("dataSource.removeAbandoned")) {
				basicDataSource.setRemoveAbandoned(Boolean.valueOf(properties
						.getProperty("dataSource.removeAbandoned")));
			}
			if (null != properties
					.getProperty("dataSource.removeAbandonedTimeout")) {
				basicDataSource
						.setRemoveAbandonedTimeout(Integer.valueOf(properties
								.getProperty("dataSource.removeAbandonedTimeout")));
			}
			if (null != properties.getProperty("dataSource.testOnBorrow")) {
				basicDataSource.setTestOnBorrow(Boolean.valueOf(properties
						.getProperty("dataSource.testOnBorrow")));
			}
			if (null != properties.getProperty("dataSource.testOnReturn")) {
				basicDataSource.setTestOnReturn(Boolean.valueOf(properties
						.getProperty("dataSource.testOnReturn")));
			}
			if (null != properties.getProperty("dataSource.testWhileIdle")) {
				basicDataSource.setTestWhileIdle(Boolean.valueOf(properties
						.getProperty("dataSource.testWhileIdle")));
			}
			if (null != properties
					.getProperty("dataSource.timeBetweenEvictionRunsMillis")) {
				basicDataSource
						.setTimeBetweenEvictionRunsMillis(Long.valueOf(properties
								.getProperty("dataSource.timeBetweenEvictionRunsMillis")));
			}
			if (null != properties.getProperty("dataSource.url")) {
				basicDataSource
						.setUrl(properties.getProperty("dataSource.url"));
			}
			if (null != properties.getProperty("dataSource.username")) {
				basicDataSource.setUsername(properties
						.getProperty("dataSource.username"));
			}
			if (null != properties.getProperty("dataSource.validationQuery")) {
				basicDataSource.setValidationQuery(properties
						.getProperty("dataSource.validationQuery"));
			}
			if (null != properties
					.getProperty("dataSource.validationQueryTimeout")) {
				basicDataSource
						.setValidationQueryTimeout(Integer.valueOf(properties
								.getProperty("dataSource.validationQueryTimeout")));
			}

			dataSource = basicDataSource;
			
			Connection conn = getConn();
			DatabaseMetaData mdm = conn.getMetaData();
			LOG.info("Connected to " + mdm.getDatabaseProductName() + " "
			+ mdm.getDatabaseProductVersion());
			if (conn != null) {
				conn.close();
			}
		} catch (Exception e) {
			LOG.error("初始化连接池失败:" + e);
		}
	}
	
	
	public static final Connection getConn() {
		Connection conn = null;
		try {
			conn = dataSource.getConnection();
		} catch (SQLException e) {
			LOG.error("获取数据库连接失败:" + e);
		}
		return conn;
	}
	
	
	public static void closeConn(Connection conn) {
		try {
			if (conn != null && !conn.isClosed()) {
				conn.setAutoCommit(true);
				conn.close();
			}
		} catch (SQLException e) {
			LOG.error("关闭数据库连接失败:" + e);
		}
	}
}
package javacommon.base;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;


public class PropertiesHandler {
	
	
	public static Properties readPropertiesFile(String filename)  
	{  
	    Properties properties = new Properties();  
	    try  
	    {  
	        InputStream inputStream = new FileInputStream(filename);  
	        properties.load(inputStream);  
	        inputStream.close(); //关闭流  
	    }  
	    catch (IOException e)  
	    {
	        e.printStackTrace();  
	    }
	    
	    return properties;
	}
}


您可能感兴趣的文档:

--结束END--

本文标题: JDBC连接数据库实例

本文链接: https://www.lsjlt.com/news/36983.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • oracle怎么查询当前用户所有的表
    要查询当前用户拥有的所有表,可以使用以下 sql 命令:select * from user_tables; 如何查询当前用户拥有的所有表 要查询当前用户拥有的所有表,可以使...
    99+
    2024-05-15
    oracle
  • oracle怎么备份表中数据
    oracle 表数据备份的方法包括:导出数据 (exp):将表数据导出到外部文件。导入数据 (imp):将导出文件中的数据导入表中。用户管理的备份 (umr):允许用户控制备份和恢复过程...
    99+
    2024-05-15
    oracle
  • oracle怎么做到数据实时备份
    oracle 实时备份通过持续保持数据库和事务日志的副本来实现数据保护,提供快速恢复。实现机制主要包括归档重做日志和 asm 卷管理系统。它最小化数据丢失、加快恢复时间、消除手动备份任务...
    99+
    2024-05-15
    oracle 数据丢失
  • oracle怎么查询所有的表空间
    要查询 oracle 中的所有表空间,可以使用 sql 语句 "select tablespace_name from dba_tablespaces",其中 dba_tabl...
    99+
    2024-05-15
    oracle
  • oracle怎么创建新用户并赋予权限设置
    答案:要创建 oracle 新用户,请执行以下步骤:以具有 create user 权限的用户身份登录;在 sql*plus 窗口中输入 create user identified ...
    99+
    2024-05-15
    oracle
  • oracle怎么建立新用户
    在 oracle 数据库中创建用户的方法:使用 sql*plus 连接数据库;使用 create user 语法创建新用户;根据用户需要授予权限;注销并重新登录以使更改生效。 如何在 ...
    99+
    2024-05-15
    oracle
  • oracle怎么创建新用户并赋予权限密码
    本教程详细介绍了如何使用 oracle 创建一个新用户并授予其权限:创建新用户并设置密码。授予对特定表的读写权限。授予创建序列的权限。根据需要授予其他权限。 如何使用 Oracle 创...
    99+
    2024-05-15
    oracle
  • oracle怎么查询时间段内的数据记录表
    在 oracle 数据库中查询指定时间段内的数据记录表,可以使用 between 操作符,用于比较日期或时间的范围。语法:select * from table_name wh...
    99+
    2024-05-15
    oracle
  • oracle怎么查看表的分区
    问题:如何查看 oracle 表的分区?步骤:查询数据字典视图 all_tab_partitions,指定表名。结果显示分区名称、上边界值和下边界值。 如何查看 Oracle 表的分区...
    99+
    2024-05-15
    oracle
  • oracle怎么导入dump文件
    要导入 dump 文件,请先停止 oracle 服务,然后使用 impdp 命令。步骤包括:停止 oracle 数据库服务。导航到 oracle 数据泵工具目录。使用 impdp 命令导...
    99+
    2024-05-15
    oracle
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作