Advertisement
Guest User

Untitled

a guest
Jan 8th, 2016
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.33 KB | None | 0 0
  1. public class Database {
  2.  
  3. private Connection connection = null;
  4. private PreparedStatement preparedStatement = null;
  5. private ResultSet resultSet = null;
  6.  
  7. // Method for registering a new account. Credentials are added into the database.
  8. public void registerAccount(String username, String password, String ipAddress) {
  9.  
  10. try {
  11.  
  12. Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
  13. connection = DriverManager
  14. .getConnection("jdbc:derby:C:\DB;create=true;upgrade=true");
  15. String query = "INSERT INTO Users (username, password, ip_address) VALUES" + "(?,?,?)";
  16. preparedStatement = connection.prepareStatement(query);
  17. preparedStatement.setString(1, username);
  18. preparedStatement.setString(2, password);
  19. preparedStatement.setString(3, ipAddress);
  20. preparedStatement.executeUpdate();
  21.  
  22. } catch (Exception e) {
  23. e.printStackTrace();
  24. } finally {
  25. close();
  26. }
  27.  
  28. }
  29.  
  30. private void close() {
  31.  
  32. try {
  33.  
  34. if (resultSet != null) {
  35. resultSet.close();
  36. }
  37. if (preparedStatement != null) {
  38. preparedStatement.close();
  39. }
  40. if (connection != null) {
  41. connection.close();
  42. }
  43. } catch (Exception e) {
  44. e.printStackTrace();
  45. }
  46.  
  47. }
  48.  
  49. // Checks if credetials are correct.
  50. public boolean checkLogin(String username, String password) {
  51.  
  52. try {
  53.  
  54. Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
  55. connection = DriverManager
  56. .getConnection("jdbc:derby:C:\DB;create=true;upgrade=true");
  57. String query = "SELECT username, password from Users WHERE username = ? AND password = ?";
  58. preparedStatement = connection.prepareStatement(query);
  59. preparedStatement.setString(1, username);
  60. preparedStatement.setString(2, password);
  61. resultSet = preparedStatement.executeQuery();
  62.  
  63. if (resultSet.next()) {
  64. String user = resultSet.getString("username");
  65. String pass = resultSet.getString("password");
  66. if (username.equalsIgnoreCase(user)) {
  67. if (password.equals(pass)) {
  68. return true;
  69. }
  70. }
  71. }
  72.  
  73. } catch (Exception e) {
  74. e.printStackTrace();
  75. } finally {
  76. close();
  77. }
  78. return false;
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement