jeudi 26 mars 2015

How to change structure to JDBC template?

How can I use JDBC template and locate it in separate class. I want to make connection with DB in one place and share it to other classes.


Thank you for help and attention!


Here is one of methods from view bean, which calls methods from dao class.



public String addNewUser() {
ELContext elContext = FacesContext.getCurrentInstance().getELContext();
ViewBean viewBean = (ViewBean) FacesContext.getCurrentInstance().getApplication().getELResolver().getValue(elContext, null, "viewBean");
UserDao ud = new UserDao();
ud.addUserToDb(viewBean.getUser());
return sessionBean.redirectToLogin();}


This is my dao class



public void addUserToDb(User user) {
int i = 0;
PreparedStatement ps = null;
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/mrktplc";
con = DriverManager.getConnection(url, "root", "qwer1234");
if (con != null) {
String sql = "INSERT INTO user_account(user_name, family_name, login, password, email) VALUES(?,?,?,?,?)";
ps = con.prepareStatement(sql);

ps.setString(1, user.getUserName());
ps.setString(2, user.getFamilyName());
ps.setString(3, user.getLoginName());
ps.setString(4, user.getPassword());
ps.setString(5, user.getEmail());
i = ps.executeUpdate();
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "User added successfully", ""));
System.out.println("User added successfully");
}
} catch (Exception e) {
System.out.println(e);
} finally {
try {
con.close();
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

public void updateUserInDb (User user) {
int i = 0;
PreparedStatement ps = null;
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/mrktplc";
con = DriverManager.getConnection(url, "root", "qwer1234");
if (con != null) {
System.out.println(user.getUserName());

String sql = "UPDATE user_account SET user_name=?, family_name=?, email=?, address=?, photo=? WHERE user_account_id=" + user.getUserId() + "";
ps = con.prepareStatement(sql);
ps.setString(1, user.getUserName());
ps.setString(2, user.getFamilyName());
ps.setString(3, user.getEmail());

ps.setString(4, user.getAddress());
String fileName = null;
if (user.getUploadedFile() != null) {
fileName = new FileUploader().fileUpload(user.getUploadedFile());
}
ps.setString(5, fileName);

i = ps.executeUpdate();
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Info", "User updated successfully!"));
System.out.println("Personal data is updated");
}

} catch (Exception e) {
System.out.println(e);
} finally {
try {
con.close();
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

Aucun commentaire:

Enregistrer un commentaire