![JAR search and dependency download from the Maven repository](/logo.png)
cn.ubibi.jettyboot.framework.jdbc.DBAccess Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of jettyboot Show documentation
Show all versions of jettyboot Show documentation
jetty boot Library, simple mvc and data ORM framework
package cn.ubibi.jettyboot.framework.jdbc;
import cn.ubibi.jettyboot.framework.commons.BeanUtils;
import javax.sql.DataSource;
import java.sql.*;
import java.util.*;
public class DBAccess {
private DataSource dataSource;
private Connection connection;
private boolean autoClose;
public DBAccess(DataSource dataSource) {
this.dataSource = dataSource;
this.autoClose = true;
}
public DBAccess(Connection connection) {
this.connection = connection;
this.autoClose = false;
}
public static DBAccess use(Connection connection){
return new DBAccess(connection);
}
// INSERT, UPDATE, DELETE 操作都可以包含在其中
public void update(String sql, Object... args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = getConnection();
preparedStatement = connection.prepareStatement(sql);
for (int i = 0; i < args.length; i++) {
preparedStatement.setObject(i + 1, args[i]);
}
preparedStatement.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
release(null, preparedStatement, connection);
}
}
/**
* 返回某条记录的某一个字段的值 或 一个统计的值(一共有多少条记录等.)
* @param sql
* @param args
* @param
* @return
*/
public E queryValue(String sql, Object... args) {
//1. 得到结果集: 该结果集应该只有一行, 且只有一列
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
//1. 得到结果集
connection = getConnection();
preparedStatement = connection.prepareStatement(sql);
for (int i = 0; i < args.length; i++) {
preparedStatement.setObject(i + 1, args[i]);
}
resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
return (E) resultSet.getObject(1);
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
release(resultSet, preparedStatement, connection);
}
//2. 取得结果
return null;
}
// 查询一条记录, 返回对应的对象
public T queryObject(Class clazz, String sql, Object... args) throws Exception {
List result = query(clazz, sql, args);
if (result.size() > 0) {
return result.get(0);
}
return null;
}
/**
* 传入 SQL 语句和 Class 对象, 返回 SQL 语句查询到的记录对应的 Class 类的对象的集合
*
* @param clazz: 对象的类型
* @param sql: SQL 语句
* @param args: 填充 SQL 语句的占位符的可变参数.
* @return
*/
public List query(Class clazz, String sql, Object... args) throws Exception {
List
© 2015 - 2025 Weber Informatics LLC | Privacy Policy