英文:
How can I retrieve the actual SQL query generated by Kotlin Exposed Library for MySQL?
问题
有没有一种方法可以知道 Kotlin Exposed Library 形成的实际 SQL 查询,在数据库上执行了什么。
我们也可以通过性能分析工具获取在数据库上执行的查询,但我更感兴趣的是 Exposed Library 是否提供了一种方法来做到这一点。
对于在代码中形成的复杂查询,我希望能够获取实际的 SQL 查询语句。
英文:
Is there a way we could know the actual sql query formed by Kotlin Exposed Library, that get's executed on database .
We could also get the query executed on database by profilers , but i'm more interested if Exposed Library provides a way to do it.
For complex queries formed in code , I wish to get the actual sql query formed
答案1
得分: 2
假设您在transaction{}块中运行对表的查询,您可以向事务块添加一个日志记录器。
transaction{}有一个名为addLogger()的扩展函数,它接受SqlLogger作为参数。
您可以添加StdOutSqlLogger,它是随Exposed库一起提供的默认SqlLogger。
以下是一个示例:
fun getAllItemsFromDb(): List<Items> {
return transaction {
addLogger(StdOutSqlLogger) // 添加一个记录SQL语句的日志记录器
Items
.selectAll().let {
fromResultRowToItems(it)
}
}
}
每当调用getAllItemsFromDb()时,日志记录器将把生成的SQL日志记录到控制台。
您还可以通过实现SqlLogger接口并重写log函数来更精细地控制SQL日志记录:
object MyQueryLogger : SqlLogger {
override fun log(context: StatementContext, transaction: Transaction) {
// 自定义日志记录方式,例如使用SLF4j
val logger = LoggerFactory.getLogger(javaClass)
logger.info("SQL: ${context.expandArgs(transaction)}")
logger.trace("SQL: ${context.expandArgs(transaction)}")
}
}
然后,在您的transaction{}中添加您的自定义日志记录器:
fun getAllItemsFromDb(): List<Items> {
return transaction {
addLogger(MyQueryLogger) // 添加您的自定义日志记录器
Items
.selectAll().let {
fromResultRowToItems(it)
}
}
}
英文:
Assuming you run queries on your table in transaction{} blocks, you can add a Logger to your transaction block.
transaction{} has an extension function called addLogger() which takes SqlLogger.
You can add the StdOutSqlLogger which is the default SqlLogger that comes with the exposed library.
Here's an example;
fun getAllItemsFromDb(): List<Items> {
return transaction {
addLogger(StdOutSqlLogger) // Adds a logger that logs SQL statements
Items
.selectAll().let {
fromResultRowToItems(it)
}
}
}
Anytime getAllItemsFromDb() is called, the logger will log the generated SQL to the console
You can also have more fine-grained control over logging your sql logging by implementing the SqlLogger interface and overriding the log function;
object MyQueryLogger : SqlLogger {
override
fun log(context: StatementContext, transaction: Transaction) {
//Customize how you want your logging, for example, using SLF4j
val logger = LoggerFactory.getLogger(javaClass)
logger.info("SQL: ${context.expandArgs(transaction)}")
logger.trace("SQL: ${context.expandArgs(transaction)}")
}
}
And then in your transaction{} add your custom Logger
fun getAllItemsFromDb(): List<Items> {
return transaction {
addLogger(MyQueryLogger ) // Add your custom logger
Items
.selectAll().let {
fromResultRowToItems(it)
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论