54 lines
1.6 KiB
Kotlin
54 lines
1.6 KiB
Kotlin
package com.example.saipp.data
|
|
|
|
import android.util.Log
|
|
import kotlinx.coroutines.Dispatchers
|
|
import kotlinx.coroutines.withContext
|
|
import java.sql.Connection
|
|
import java.sql.DriverManager
|
|
import java.sql.SQLException
|
|
import java.util.Properties
|
|
|
|
object MariaDbConnection {
|
|
private const val TAG = "MariaDbConnection"
|
|
|
|
// TODO: Replace with your actual database details
|
|
private const val HOST = "mariadb.peta9.com"
|
|
private const val PORT = "3306"
|
|
private const val DATABASE = "sais_db"
|
|
private const val USER = "sais_dba"
|
|
private const val PASSWORD = "Pedro@110387"
|
|
|
|
private const val URL = "jdbc:mariadb://$HOST:$PORT/$DATABASE"
|
|
|
|
fun getConnection(): Connection? {
|
|
return try {
|
|
// Load the driver explicitly if needed
|
|
Class.forName("org.mariadb.jdbc.Driver")
|
|
|
|
val props = Properties()
|
|
props.setProperty("user", USER)
|
|
props.setProperty("password", PASSWORD)
|
|
props.setProperty("connectTimeout", "5000") // 5 seconds timeout
|
|
|
|
DriverManager.getConnection(URL, props)
|
|
} catch (e: Exception) {
|
|
Log.e(TAG, "Error connecting to MariaDB: ${e.message}", e)
|
|
null
|
|
}
|
|
}
|
|
|
|
suspend fun testConnection(): Result<Unit> = withContext(Dispatchers.IO) {
|
|
val connection = getConnection()
|
|
if (connection != null) {
|
|
try {
|
|
connection.close()
|
|
Result.success(Unit)
|
|
} catch (e: SQLException) {
|
|
Result.failure(e)
|
|
}
|
|
} else {
|
|
Result.failure(Exception("connection_failed"))
|
|
}
|
|
}
|
|
}
|