我正在使用Servlet和JSP執行CRUD操作。以下類用於從服務器(Tomcat)維護的連接池中檢索連接。使用Servlet/JSP執行CRUD操作
public final class DatabaseConnection {
private static final DataSource dataSource;
static {
try {
Context initContext = new InitialContext();
Context context = (Context) initContext.lookup("java:/comp/env");
dataSource = (DataSource) context.lookup("jdbc/assignment_db");
} catch (NamingException e) {
Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, e);
throw new ExceptionInInitializerError("DataSource not initialized.");
}
}
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
}
以下類(DAO)中的方法執行CRUD操作。
public final class CountryDao {
public Long getCurrentRow(Long id) throws SQLException {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = DatabaseConnection.getConnection();
preparedStatement = connection.prepareStatement("select rownum from (select @rownum:[email protected]+1 as rownum, tbl.country_id from country_tbl tbl, (select @rownum:=0)t order by tbl.country_id desc)t where country_id=?");
preparedStatement.setLong(1, id);
resultSet = preparedStatement.executeQuery();
return resultSet.next() ? resultSet.getLong("rownum") : 1;
} finally {
if (connection != null) {connection.close();}
if (resultSet != null) {resultSet.close();}
if (preparedStatement != null) {preparedStatement.close();}
}
}
public Long rowCount() throws SQLException {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = DatabaseConnection.getConnection();
preparedStatement = connection.prepareStatement("select count(*) as cnt from country_tbl");
resultSet = preparedStatement.executeQuery();
resultSet.next();
return resultSet.getLong("cnt");
} finally {
if (connection != null) {connection.close();}
if (resultSet != null) {resultSet.close();}
if (preparedStatement != null) {preparedStatement.close();}
}
}
public List<CountryBean> getData(Long currentPage, Long pageSize) throws SQLException {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
List<CountryBean> countryBeans = new ArrayList<CountryBean>();
try {
connection = DatabaseConnection.getConnection();
preparedStatement = connection.prepareStatement("select * from country_tbl order by country_id desc limit ?,?");
//preparedStatement.setMaxRows(pageSize);
preparedStatement.setLong(1, currentPage);
preparedStatement.setLong(2, pageSize);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
CountryBean countryBean = new CountryBean();
countryBean.setCountryId(resultSet.getLong("country_id"));
countryBean.setCountryName(resultSet.getString("country_name"));
countryBean.setCountryCode(resultSet.getString("country_code"));
countryBeans.add(countryBean);
}
} finally {
if (connection != null) {connection.close();}
if (resultSet != null) {resultSet.close();}
if (preparedStatement != null) {preparedStatement.close();}
}
return countryBeans;
}
public boolean delete(Long id) throws SQLException {
boolean status = false;
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = DatabaseConnection.getConnection();
preparedStatement = connection.prepareStatement("delete from country_tbl where country_id=?");
preparedStatement.setLong(1, id);
if (preparedStatement.executeUpdate() == 1) {
status = true;
}
} finally {
if (connection != null) {connection.close();}
if (preparedStatement != null) {preparedStatement.close();}
}
return status;
}
public boolean delete(Long[] ids) throws SQLException {
boolean status = false;
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = DatabaseConnection.getConnection();
connection.setAutoCommit(false);
preparedStatement = connection.prepareStatement("delete from country_tbl where country_id=?");
int len = ids.length;
for (int i = 0; i < len; i++) {
preparedStatement.setLong(1, ids[i]);
preparedStatement.addBatch();
}
preparedStatement.executeBatch();
connection.commit();
status = true;
} finally {
if (connection != null) {connection.close();}
if (preparedStatement != null) {preparedStatement.close();}
}
return status;
}
public boolean insert(String countryName, String countryCode) throws SQLException {
boolean status = false;
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = DatabaseConnection.getConnection();
preparedStatement = connection.prepareStatement("insert into country_tbl(country_name, country_code)values(?,?)");
preparedStatement.setString(1, countryName);
preparedStatement.setString(2, countryCode);
preparedStatement.executeUpdate();
status = true;
} finally {
if (connection != null) {connection.close();}
if (preparedStatement != null) {preparedStatement.close();}
}
return status;
}
public boolean update(Long countryId, String countryName, String countryCode) throws SQLException {
boolean status = false;
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = DatabaseConnection.getConnection();
preparedStatement = connection.prepareStatement("update country_tbl set country_name=?, country_code=? where country_id=?");
preparedStatement.setString(1, countryName);
preparedStatement.setString(2, countryCode);
preparedStatement.setLong(3, countryId);
preparedStatement.executeUpdate();
status = true;
} finally {
if (connection != null) {connection.close();}
if (preparedStatement != null) {preparedStatement.close();}
}
return status;
}
}
這些方法在執行驗證後從Servlet中被適當調用。反過來,Servlet與JSP(與JSTL/EL一起)進行交互。
只有一個問題。很遺憾,connection
,preparedStatement
和resultSet
都是局部變量到特定方法。
我可以僅在一個地方聲明它們作爲類成員(實例變量)嗎?這樣做能夠保持一致的狀態嗎?
沒有必要把精力集中在覈心邏輯上。請不要只是說,最好使用MVC框架:)
哎,我不明白您的問題...只是試試這個,HTTP:// publib .boulder.ibm.com/infocenter/db2luw/v8/index.jsp?topic =/com.ibm.db2.udb.doc/ad/tjvpsxqu.htm,http://docs.oracle.com/javase/7/ docs/api/java/sql/PreparedStatement.html – jmail
我很想知道這一點。給出的代碼沒有問題。 – Tiny