Advertisement
Guest User

Untitled

a guest
Feb 2nd, 2019
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.57 KB | None | 0 0
  1. class Database(host: String, port: String, database: String, userName: String,
  2. password: String, private val table: String) {
  3.  
  4. private var dataSource = HikariDataSource()
  5.  
  6. init {
  7. dataSource.maximumPoolSize = 3
  8. dataSource.connectionTimeout = 30000
  9. dataSource.jdbcUrl = "jdbc:mysql://$host:$port/$database"
  10. dataSource.username = userName
  11. dataSource.password = password
  12. dataSource.addDataSourceProperty("cachePrepStmts", true)
  13. dataSource.addDataSourceProperty("prepStmtCacheSize", 250)
  14. dataSource.addDataSourceProperty("prepStmtCacheSqlLimit", 2048)
  15. dataSource.addDataSourceProperty("useServerPrepStmts", true)
  16. }
  17.  
  18. private fun createTable() {
  19. val connection = dataSource.connection
  20. val stmt = connection.prepareStatement("CREATE TABLE IF NOT EXISTS `$table` (`uuid` VARCHAR(36) NOT NULL, " +
  21. "`walletData` TEXT NOT NULL, PRIMARY KEY(uuid));")
  22. stmt.executeUpdate()
  23. connection.close()
  24. }
  25.  
  26. fun loadUsers() {
  27.  
  28. createTable()
  29.  
  30. val connection = dataSource.connection
  31. val stmt = connection.prepareStatement("SELECT * FROM `$table`")
  32. val resultSet = stmt.executeQuery()
  33.  
  34. while (resultSet.next()) {
  35.  
  36. val uuid = UUID.fromString(resultSet.getString("uuid"))
  37. val user = EconomyUserUtils.getUserOrCreate(uuid)
  38.  
  39. for (walletEntry in resultSet.getString("walletData").split(";")) {
  40.  
  41. val entrySplit = walletEntry.split(",")
  42. val currency = CurrencyUtils.getCurrencyByName(entrySplit[0]) ?: continue
  43.  
  44. user.wallet.openWalletIn(currency)
  45. user.wallet.getCurrencyValue(currency)!!.set(CurrencyValueImpl(entrySplit[1].toInt(), entrySplit[2].toInt()), currency.currencyDivision)
  46.  
  47. }
  48. }
  49.  
  50. resultSet.close()
  51. connection.close()
  52.  
  53. }
  54.  
  55. fun saveUser(user: EconomyUser) {
  56.  
  57. createTable()
  58.  
  59. val connection = dataSource.connection
  60.  
  61. val uuid = user.uuid.toString()
  62. var walletData = ""
  63.  
  64. for (walletEntry in user.wallet.currencies) {
  65.  
  66. walletData += ";${walletEntry.first.majorName.name},${walletEntry.second.major},${walletEntry.second.minor}"
  67.  
  68. }
  69.  
  70. walletData = walletData.substring(1)
  71.  
  72. val stmt = connection.prepareStatement("INSERT INTO `$table` VALUES('$uuid', '$walletData') ON DUPLICATE KEY UPDATE walletData=$walletData")
  73. stmt.executeUpdate()
  74. connection.close()
  75.  
  76. }
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement