有没有办法用Kotlin的公开库运行原始sql

bpzcxfmw  于 2022-12-19  发布在  Kotlin
关注(0)|答案(5)|浏览(102)

我正在尝试运行一些特定于postgres的sql,并希望重用Exposed中的事务管理。

6ovsh4lw

6ovsh4lw1#

Exposed具有Transaction.exec(String)方法,它可能会执行您想要的操作。

rdlzhqv9

rdlzhqv92#

在Kiskae答案的帮助下,我能够运行原始sql:

transaction {
     val conn = TransactionManager.current().connection
     val statement = conn.createStatement()
     val query = "REFRESH MATERIALIZED VIEW someview"
     statement.execute(query)
}
35g0bw71

35g0bw713#

import java.sql.*
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.transactions.*

fun getAccId(db : Database, acc_domain: String) {
  transaction(db) {
    addLogger(StdOutSqlLogger)
    var acc_id: Long = 0
    exec("select id from accounts where domain = '${acc_domain}'") { rs ->
        while(rs.next()) {
          acc_id = rs.getLong("id")
        }
    }
    println("Acc Id is ${acc_id}")
  }
}

val database = Database.connect(datasource)
getAccId(database,"mytest.test.io")
imzjd6km

imzjd6km4#

下面是一个带有参数的示例:

transaction(database) {
   val conn = TransactionManager.current().connection
   val query = "update user set name = ? where id = ?";
   val statement = conn.prepareStatement(query, false)
   statement.fillParameters(listOf(Pair(VarCharColumnType(), "Laura"),
      Pair(IntegerColumnType(), 3)));
   statement.executeUpdate()
}
yv5phkfx

yv5phkfx5#

您可以创建一个简单的辅助函数,如:

fun <T : Any> String.execAndMap(transform: (ResultSet) -> T): List<T> {
    val result = arrayListOf<T>()
    TransactionManager.current().exec(this) { rs ->
        while (rs.next()) {
            result += transform(rs)
        }
    }
    return result
}
"select u.name, c.name from user u inner join city c where blah blah".execAndMap { rs ->
    rs.getString("u.name") to rs.getString("c.name")
}

摘自:https://github.com/JetBrains/Exposed/wiki/FAQ#q-is-it-possible-to-use-native-sql--sql-as-a-string

相关问题