ユーザーデータをフォームからデータベースに保存し、要求に応じてデータベースのコンテンツをブラウザーに読み戻す簡単なWebアプリを作成しようとしています。これまでに書いた関数は次のとおりです。
connectToDB() // connects to database
addEmployee() // adds employee to database
displayEmployee() // returns a resultSet
isExisted(int staffID) // checks if the staff already exists
データベース接続機能:
public void connectToDB(){
try{
// load Apache derby driver
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
} catch(ClassNotFoundException e) {
System.err.println(e);
}
try{
connection = DriverManager.getConnection(DBNAME, USERNAME, PASSWORD);
} catch(SQLException e){
System.err.println(e);
}
} // end connectToDB
従業員機能の表示:
public ResultSet displayEmployee(){
connectToDB();
ResultSet result = null;
try{
Statement stmt = connection.createStatement();
String query = "SELECT * FROM APP.ADDRESSBOOK";
result = stmt.executeQuery(query);
} catch(SQLException e) {
System.err.println(e);
}
return result;
}
従業員が存在するかどうかを確認します。
public boolean isExisted(int StaffID){
connectToDB();
try{
Statement stmt = connection.createStatement();
String query = "SELECT StaffNum FROM APP.ADDRESSBOOK WHERE StaffNum = " + staff_number;
ResultSet result = stmt.executeQuery(query);
while(result.next()){
int temp = result.getInt(1);
if(temp == staff_number){return true;}
}
} catch(SQLException e) {
System.err.println(e);
}
return false;
}
ご覧のとおり、とを比較するdisplayEmployee()
とisExisted()
、私は自分自身を繰り返しています。どちらの関数も機能しますが、コードをリファクタリングしようとしています。それらの関数では、接続を閉じていません。データベースに接続するWebアプリに20個の関数がある場合、私のコードは悪臭を放ちます。
私はこのようなものを探しています: *このコードは機能しません* ** * **
private Statement queryDB(query){
connectToDB();
Statement stmt;
try{
stmt = connection.createStatement();
} catch(SQLException e) {
System.err.println(e);
}
return stmt;
// code for closing connection
}
public ResultSet DisplayEmployee(){
String query = "SELECT * FROM APP.ADDRESSBOOK";
Statement stmt = queryDB(query);
ResultSet result = stmt.executeQuery(query);
return result;
}
ありがとう。