Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
- package com.spec.service;
- import com.spec.DBUtil;
- import com.spec.model.UserAccount;
- import java.sql.Connection;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.ResultSetMetaData;
- import java.sql.SQLException;
- import java.sql.Statement;
- import java.util.List;
- public class UserAccountService implements IUserAccountService{
- @Override
- public int createAccount(UserAccount user) throws Exception {
- //
- int pk = 0;
- final String sql = "INSERT INTO accounts (username, password, email, created_on, last_login) " +
- "VALUES(?, ?, ?, now(), NULL)";
- try(Connection c = DBUtil.getConn();
- PreparedStatement ps = c.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);){
- // установка параметра userName
- ps.setString(1, user.getUserName());
- ps.setString(2, user.getPassword());
- ps.setString(3, user.getEmail());
- // выполнение запроса
- int res = ps.executeUpdate();
- System.out.println("createAccount.res=" + res);
- //
- try(ResultSet rs = ps.getGeneratedKeys()){
- ResultSetMetaData meta = rs.getMetaData();
- System.out.println("meta.getColumnCount()=" + meta.getColumnCount());
- for (int i = 1; i <= meta.getColumnCount(); i++) {
- System.out.println("meta.colName=" + meta.getColumnName(i));
- }
- if(rs.next()){
- //pk = rs.getInt(1);
- pk = rs.getInt("user_id");
- System.out.println("createAccount.pk=" + pk);
- }
- }
- }catch(SQLException ex){
- ex.printStackTrace();
- throw new Exception("error while createAccount", ex);
- }
- return pk;
- }
- @Override
- public boolean setAccount(UserAccount user) throws Exception {
- return true;
- }
- @Override
- public void removeAccount(String userName) throws Exception {
- // -- DELETE
- final String sql = "DELETE FROM accounts WHERE username=?";
- try(Connection c = DBUtil.getConn();
- PreparedStatement ps = c.prepareStatement(sql);){
- // установка параметра userName
- ps.setString(1, userName);
- // выполнение запроса
- int res = ps.executeUpdate();
- System.out.println("removeAccount.res=" + res);
- }catch(SQLException ex){
- ex.printStackTrace();
- throw new Exception("error while removeAccount", ex);
- }
- }
- @Override
- public UserAccount getUserAccount(String userName) {
- return null;
- }
- @Override
- public List<UserAccount> getAll() {
- return null;
- }
- @Override
- public List<UserAccount> findAccounts(Object /*Filter*/ filter) {
- return null;
- }
- //
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement