Advertisement
Guest User

Untitled

a guest
Jan 8th, 2016
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.47 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.  
  50. // Checks if credetials are correct.
  51. public boolean checkLogin(String username, String password) {
  52.  
  53. try {
  54.  
  55. Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
  56. connection = DriverManager
  57. .getConnection("jdbc:derby:C:\DB;create=true;upgrade=true");
  58. String query = "SELECT username, password from Users WHERE username = ? AND password = ?";
  59. preparedStatement = connection.prepareStatement(query);
  60. preparedStatement.setString(1, username);
  61. preparedStatement.setString(2, password);
  62. resultSet = preparedStatement.executeQuery();
  63.  
  64. if (resultSet.next()) {
  65. String user = resultSet.getString("username");
  66. String pass = resultSet.getString("password");
  67. if (username.equalsIgnoreCase(user)) {
  68. if (password.equals(pass)) {
  69. return true;
  70. }
  71. }
  72. }
  73.  
  74. } catch (Exception e) {
  75. e.printStackTrace();
  76. } finally {
  77. close();
  78. }
  79. return false;
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement