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

时间:2016-12-05 19:26:55

标签: kotlin kotlin-exposed

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

5 个答案:

答案 0 :(得分:8)

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

Sub GetKeyRatios()
Dim URL As String, csv As String, Lines, Values
Dim i As Long, j As Long, WinHttpReq As Object
Dim rngStart As Range

URL = "http://financials.morningstar.com/ajax/exportKR2CSV.html?&callback=?&t=XNYS:JNJ&region=usa&culture=en-US&cur=USD&order=asc"

Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
WinHttpReq.Open "GET", URL, False
WinHttpReq.send

csv = WinHttpReq.responseText

Lines = Split(csv, vbLf)

Set rngPaste = Sheets("KeyRatios").Range("A1")

For i = 0 To UBound(Lines)
    Values = Split(Lines(i), ",")
    For j = 0 To UBound(Values)
        rngPaste.Offset(i, j).Value = Values(j)
    Next j
Next i
End Sub

答案 1 :(得分:6)

答案 2 :(得分:1)

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")

答案 3 :(得分:1)

下面是带有参数的示例:

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()
}

答案 4 :(得分:0)

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

 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") 
    } 

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