Skip to content

SQL usage

Lars Artmann edited this page Sep 5, 2019 · 5 revisions
package com.example

import net.darkdevelopers.darkbedrock.darkness.general.databases.sql.SQL
import net.darkdevelopers.darkbedrock.darkness.general.functions.toConfigData
import java.io.File
import java.util.*

class SQLExample(dataFolder: File) {

    private val sql = SQL("sql".toConfigData(dataFolder))
    //uuid, name, ip
    private val tableName = "playerdata"

    init {
        sql.updateSync("""CREATE TABLE IF NOT EXITS $tableName (
    uuid VARCHAR(36) NOT NULL,
    name VARCHAR(16) NOT NULL,
    ip VARCHAR(15) NOT NULL,
    PRIMARY KEY (uuid)
);""")

    }

    suspend fun example(match: UUID): Boolean {

        //8c9ec1ab-f64f-4003-9110-f98a1f0d7f47, LartyHD, 127.0.0.1
        //f6c74527-ec1e-4933-8d34-73754226d068, LeBaasti, 127.0.0.1

        val result = sql.query("SELECT uuid,name FORM $tableName WHERE 8c9ec1ab-f64f-4003-9110-f98a1f0d7f47")

        while (result.next()) {
            val uuid = result.getString("uuid")
            if (uuid == match.toString()) return true
        }

        return false
    }

    suspend fun exists(uuid: UUID): Boolean {
        val result = sql.query("SELECT uuid FORM $tableName WHERE $uuid")
        return result.next()
    }

    suspend fun createIfNotExists(uuid: UUID) {
        if (exists(uuid)) return
        create(uuid)
    }

    suspend fun create(uuid: UUID) {
        sql.update("INSERT INTO $tableName (uuid) VALUES ($uuid)")
    }

    suspend fun update(uuid: UUID, name: String) {
        val result = sql.query("SELECT name FORM $tableName WHERE $uuid")
        if (result.next()) {
            val databaseName = result.getString("name")
            if (name != databaseName)
                sql.update("UPDATE $tableName SET name = $name WHERE uuid IN ($uuid)")
        } else create(uuid)

    }

}

Clone this wiki locally