Is there a way to run raw sql with Kotlin's Exposed library

时光毁灭记忆、已成空白 提交于 2020-05-14 21:51:43

问题


I'm trying to run some sql specific to postgres and would like to reuse the transaction management within Exposed.


回答1:


With help from Kiskae's answer, I was able to run the raw sql with:

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



回答2:


Exposed has the Transaction.exec(String) method which probably does what you want. See https://github.com/JetBrains/Exposed/blob/master/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/mysql/MysqlTests.kt




回答3:


You can create a simple helper function like:

 String.execAndMap(transform : (ResultSet) -> T) : List {
         val result = arrayListOf()
         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") 
    } 

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



来源:https://stackoverflow.com/questions/40981804/is-there-a-way-to-run-raw-sql-with-kotlins-exposed-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!