Untitled
unknown
java
a year ago
1.4 kB
7
Indexable
package org.example import com.mysql.cj.jdbc.Driver import java.io.Closeable import java.io.IOException import java.sql.Connection import java.sql.DriverManager import java.sql.SQLException class MySqlConnector(url: String, port: Int, dbName: String, username: String, password: String) : Closeable { val connection: Connection init { val dbUrl = ("jdbc:mysql://" + url + ":" + port + "/" + dbName + "?verifyServerCertificate=false&useSSL=false&" + "requireSSL=false&useLegacyDatetimeCode=false&&serverTimezone=UTC&createDatabaseIfNotExist=true&autoReconnect=true") this.connection = createConnection(dbUrl, username, password) } private fun createConnection(url: String, username: String, password: String): Connection { try { DriverManager.registerDriver(Driver()) return DriverManager.getConnection(url, username, password) } catch (e: SQLException) { throw RuntimeException(e) } } @Throws(IOException::class) override fun close() { try { connection.close() } catch (e: SQLException) { throw IOException(e) } } } fun main() { MySqlConnector("localhost", 3306, "bober", "root", "1234").use { mySqlConnector -> val connection = mySqlConnector.connection println(connection) } }
Editor is loading...
Leave a Comment