Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Constructor + class wide variables
- private final DBConnector dbcon;
- Password pass = new Password();
- /**
- * established connection to the database when instantiated.
- *
- * @throws Exception if anything goes wrong - see DBConnector object for
- * details.
- */
- public DataAccessObjectImpl() throws Exception {
- this.dbcon = new DBConnector(); //DBConnector is the first pastebin I sent you.
- }
- //Example on a method to retrieve information from the DB
- //Just replace user with book or whatever you feel like you need.
- //This is SQL injection safe because of prepareStatement
- public User getUserByUsername(String username) throws SQLException {
- User user = null;
- PreparedStatement stmt = null;
- try {
- stmt = dbcon.getConnection().prepareStatement("SELECT * FROM users WHERE uname = ?;");
- stmt.setString(1, username);
- ResultSet rs = stmt.executeQuery();
- if (rs.next()) {
- int UID = rs.getInt("uid");
- String usernameRetrieved = rs.getString("uname");
- String passwordRetrieved = rs.getString("password");
- String saltRetrieved = rs.getString("salt");
- String emailRetrieved = rs.getString("email");
- String userString = rs.getString("userstring");
- String carportRetrieved = rs.getString("carport");
- user = new User(UID, usernameRetrieved, passwordRetrieved, saltRetrieved, emailRetrieved, userString, carportRetrieved);
- }
- } finally {
- try {
- if (stmt != null) {
- stmt.close();
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- return user;
- }
- //Insert into the DB
- //This is SQL injection safe because of prepareStatement
- //the int parameter in the stmt.setString corresponds with the ? in the insert statement.
- //Again replace with whatever you feel necesarry
- public boolean createUser(String username, String password, String email) throws SQLException, UnsupportedEncodingException {
- PreparedStatement stmt = null;
- try {
- String passSalt = pass.getSaltString();
- stmt = dbcon.getConnection().prepareStatement("INSERT INTO users VALUES (default, ?, ?, ?, ?, ?, null)");
- stmt.setString(1, username);
- stmt.setString(2, email);
- stmt.setString(3, pass.get_SHA_512_SecurePassword(password, passSalt));
- stmt.setString(4, passSalt);
- stmt.setString(5, pass.getSaltString());
- int i = stmt.executeUpdate();
- } finally {
- try {
- if (stmt != null) {
- stmt.close();
- return true;
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- return false;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement