📄 daoutil.java
字号:
package shopping.util;
import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.sql.Connection;
public class DAOUtil {
private static final String DATASOURCE_JNDI = "java:comp/env/jdbc/shoppingtest";
private DAOUtil() {
}
private static DataSource getDataSource() throws Exception {
return (DataSource) ServiceLocator.getInstance().getDataSource(
DATASOURCE_JNDI);
}
private static DataSource getDataSource(Object callerObj) throws Exception {
return (DataSource) ServiceLocator.getInstance().getDataSource(
DATASOURCE_JNDI, callerObj);
}
private static DataSource getDataSource(String jndi) throws Exception {
return (DataSource) ServiceLocator.getInstance().getDataSource(jndi);
}
public static Connection getDBConnection() throws Exception {
try {
System.out.println("1");
return getDataSource(DATASOURCE_JNDI).getConnection();
} catch (SQLException se) {
throw new Exception("SQL Exception while getting "
+ "DB connection : \n" + se);
}
}
public static Connection getDBConnection(Object callerObj) throws Exception {
try {
return getDataSource(callerObj).getConnection();
} catch (SQLException se) {
throw new Exception("SQL Exception while getting "
+ "DB connection : \n" + se);
}
}
public static void closeConnection(Connection dbConnection) {
try {
if (dbConnection != null && !dbConnection.isClosed()) {
dbConnection.close();
}
} catch (SQLException se) {
}
}
public static void closeConnection(Connection dbConnection, Object callerObj) {
try {
if (dbConnection != null && !dbConnection.isClosed()) {
dbConnection.close();
}
} catch (SQLException se) {
se.printStackTrace();
}
}
public static void closeResultSet(ResultSet result) {
try {
if (result != null) {
result.close();
}
} catch (SQLException se) {
se.printStackTrace();
}
}
public static void closeResultSet(ResultSet result, Object callerObj) {
try {
if (result != null) {
result.close();
}
} catch (SQLException se) {
se.printStackTrace();
}
}
public static void closeStatement(PreparedStatement stmt) {
try {
if (stmt != null) {
stmt.close();
}
} catch (SQLException se) {
se.printStackTrace();
}
}
public static void closeStatement(PreparedStatement stmt, Object callerObj) {
try {
if (stmt != null) {
stmt.close();
}
} catch (SQLException se) {
se.printStackTrace();
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -