Untitled

mail@pastecode.io avatar
unknown
plain_text
22 days ago
4.7 kB
5
Indexable
Never
import com.google.common.base.Preconditions
import com.google.common.cache.CacheBuilder
import com.google.common.cache.CacheLoader
import com.google.common.cache.LoadingCache
import java.sql.*
import java.sql.Date
import java.util.concurrent.ExecutionException
import java.util.concurrent.TimeUnit

class MySQL private constructor(
    private val connectionUrl: String,
    private val database: String,
    private val user: String,
    private val password: String,
    private val port: Int
) {

    private val cache: LoadingCache<Int, Connection> = CacheBuilder.newBuilder()
        .expireAfterAccess(10, TimeUnit.SECONDS)
        .removalListener<Int, Connection> { removalNotification ->
            try {
                removalNotification.value?.close()
            } catch (e: SQLException) {
                e.printStackTrace()
            }
        }
        .build(object : CacheLoader<Int, Connection>() {
            @Throws(Exception::class)
            override fun load(integer: Int): Connection {
                return createConnection()
            }
        })

    fun update(update: String, vararg objs: Any) {
        try {
            val connection = cache.get(1)
            val p = connection.prepareStatement(update)
            setArguments(objs, p)
            p.execute()
            p.close()
        } catch (e: SQLException) {
            e.printStackTrace()
        } catch (e: ExecutionException) {
            e.printStackTrace()
        }
    }

    fun query(query: String, vararg objs: Any): ResultSet? {
        try {
            val connection = cache.get(1)
            val p = connection.prepareStatement(query)
            setArguments(objs, p)
            return p.executeQuery()
        } catch (e: SQLException) {
            e.printStackTrace()
        } catch (e: ExecutionException) {
            e.printStackTrace()
        }
        return null
    }

    @Throws(SQLException::class)
    private fun setArguments(objs: Array<out Any>, p: PreparedStatement) {
        for ((i, obj) in objs.withIndex()) {
            when (obj) {
                is String -> p.setString(i + 1, obj)
                is Int -> p.setInt(i + 1, obj)
                is Date -> p.setDate(i + 1, obj)
                is Timestamp -> p.setTimestamp(i + 1, obj)
                is Boolean -> p.setBoolean(i + 1, obj)
                is Float -> p.setFloat(i + 1, obj)
                is Double -> p.setDouble(i + 1, obj)
                is Long -> p.setLong(i + 1, obj)
            }
        }
    }

    @Throws(SQLException::class)
    private fun createConnection(): Connection {
        return DriverManager.getConnection(
            "jdbc:mysql://$connectionUrl:$port/$database?characterEncoding=utf8",
            user,
            password
        )
    }

    class Builder {
        private var connectionUrl: String? = null
        private var database: String? = null
        private var user: String? = null
        private var password: String? = null
        private var port: Int? = null

        fun withUrl(url: String): Builder {
            connectionUrl = url
            return this
        }

        fun withDatabase(database: String): Builder {
            this.database = database
            return this
        }

        fun withUser(user: String): Builder {
            this.user = user
            return this
        }

        fun withPassword(password: String): Builder {
            this.password = password
            return this
        }

        fun withPort(port: Int): Builder {
            this.port = port
            return this
        }

        fun create(): MySQL {
            Preconditions.checkNotNull(connectionUrl, "Connection URL is null")
            Preconditions.checkNotNull(database, "Database is null")
            Preconditions.checkNotNull(user, "Username is null")
            Preconditions.checkNotNull(password, "Password is null")
            Preconditions.checkNotNull(port, "Port is null")
            return MySQL(connectionUrl!!, database!!, user!!, password!!, port!!)
        }
    }

    fun get(whereresult: String, where: String, select: String, database: String): Any? {
        val qry = "SELECT $select FROM $database WHERE $where='$whereresult'"
        println("MySQL get method: $qry")
        return try {
            query(qry)?.use { rs ->
                if (rs.next()) {
                    rs.getObject(select)
                } else null
            }
        } catch (e: SQLException) {
            e.printStackTrace()
            null
        }
    }
}
Leave a Comment