基础BaseDao

Posted 盛夏光年2017

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了基础BaseDao相关的知识,希望对你有一定的参考价值。

package cn.easybuy.util;

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

import cn.easybuy.tool.ConfigManager;

/**
* Dao层的公共属性和方法
*
*/
public class BaseDao {

/* 连接数据库 */
public static Connection getConnection() {

// 连接数据库的四要素
String url = ConfigManager.getInstance().getValue("url");
String user = ConfigManager.getInstance().getValue("user");
String password = ConfigManager.getInstance().getValue("password");
String driver = ConfigManager.getInstance().getValue("driverClass");
Connection connection = null;

try {
Class.forName(driver);
connection = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return connection;

}

public static boolean closeResource(Connection connection,
PreparedStatement ps, ResultSet rs) {
boolean flag = true;
if (rs != null) {
try {
rs.close();
rs = null;// GC回收
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
flag = false;
}

}

if (ps != null) {
try {
ps.close();
ps = null;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
flag = false;
}

}
if (connection != null) {
try {
connection.close();
connection = null;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
flag = false;
}

}
return flag;

}

/**
* 查询操作
*
* @throws Exception
*/
public static ResultSet execute(Connection connection,
PreparedStatement ps, ResultSet rs, String sql, Object[] params)
throws Exception {
ps = connection.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
ps.setObject(i + 1, params[i]);
}
rs = ps.executeQuery();
return rs;
}

/**
* 更新操作
*
* @throws Exception
*/
public static int execute(Connection connection, PreparedStatement ps,
String sql, Object[] params) throws Exception {
int updateRows = 0;
ps = connection.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
ps.setObject(i + 1, params[i]);
}
updateRows = ps.executeUpdate();
return updateRows;

}
}

以上是关于基础BaseDao的主要内容,如果未能解决你的问题,请参考以下文章

基础架构基础服务基础平台基础中间件等等

Python运维开发基础01-语法基础

JAVA基础入门教程 -

iOS UIScrollView基础

Scala 基础—— 基础类型和基础操作

Linux基础——bash基础应用及文件系统基础命令