Professional Documents
Culture Documents
Kotlin Tutorial – We shall learn to connect to MySQL Database from Kotlin using JDBC with the help a Kotlin
Example Program.
Following is a step by step process explained to connect to MySQL Database from Kotlin using JDBC :
try {
stmt = conn!!.createStatement()
resultset = stmt!!.executeQuery("SHOW DATABASES;")
if (stmt.execute("SHOW DATABASES;")) {
resultset = stmt.resultSet
}
while (resultset!!.next()) {
println(resultset.getString("Database"))
}
} catch (ex: SQLException) {
// handle any errors
ex.printStackTrace()
}
/**
* Program to list databases in MySQL using Kotlin
*/
object MySQLDatabaseExampleKotlin {
fun executeMySQLQuery() {
var stmt: Statement? = null
var resultset: ResultSet? = null
try {
stmt = conn!!.createStatement()
resultset = stmt!!.executeQuery("SHOW DATABASES;")
if (stmt.execute("SHOW DATABASES;")) {
resultset = stmt.resultSet
}
while (resultset!!.next()) {
println(resultset.getString("Database"))
}
} catch (ex: SQLException) {
// handle any errors
ex.printStackTrace()
} finally {
// release resources
if (resultset != null) {
if (resultset != null) {
try {
resultset.close()
} catch (sqlEx: SQLException) {
}
resultset = null
}
if (stmt != null) {
try {
stmt.close()
} catch (sqlEx: SQLException) {
}
stmt = null
}
if (conn != null) {
try {
conn!!.close()
} catch (sqlEx: SQLException) {
}
conn = null
}
}
}
/**
* This method makes a connection to MySQL Server
* In this example, MySQL Server is running in the local host (so 127.0.0.1)
* at the standard port 3306
*/
fun getConnection() {
val connectionProps = Properties()
connectionProps.put("user", username)
connectionProps.put("password", password)
try {
Class.forName("com.mysql.jdbc.Driver").newInstance()
conn = DriverManager.getConnection(
"jdbc:" + "mysql" + "://" +
"127.0.0.1" +
":" + "3306" + "/" +
"",
connectionProps)
} catch (ex: SQLException) {
// handle any errors
ex.printStackTrace()
} catch (ex: Exception) {
// handle any errors
ex.printStackTrace()
}
}
}
Program Output
information_schema
mysql
performance_schema
studentsDB
sys
Conclusion :
In this Kotlin Tutorial, we have learnt to connect to MySQL Database from Kotlin using JDBC with the help of
Kotlin Example Program.
Kotlin Java
Kotlin Tutorial
Getting Started
Kotlin repeat
Kotlin - Ranges
Kotlin - When
Inheritance
Kotlin - Inheritance
Abstraction
Kotlin - Abstraction
Kotlin - Interfaces
Data Class
Exception Handling
Kotlin - Functions
Kotlin - Collections
Kotlin - List
Kotlin List
Kotlin - Android
Kotlin - Android
Useful Resources