I want to build a query string with coolest way `...
# getting-started
t
I want to build a query string with coolest way
Copy code
val query = "INSERT INTO table (id, name, age) VALUES (?,?,?)"
this is ordinary way (i usually use) and the problem is, the parameter `?`need to append according to the increase or decrease of column
id, name, age
so i tried,,,
Copy code
var column = "id, name, age"
val query = "INSERT INTO table (${column}) VALUES (${(1..3).forEach { ? }})"
the part
${(1..3).forEach { ? }}
is incorrect, i don’t know how to do. hope you got me,
a
Copy code
val columns = listOf("id", "name", "age")
println("INSERT INTO table (${columns.joinToString(", ")}) VALUES (${columns.map{ "?" }.joinToString(", ")})")
I think you're better off using some framework to create typesafe queries etc. though
👍 1
r
You technically don't need a separate may call
columns.joinToString(", ") { "?" }
1
👆 1
m
This is a nice excercise, but I would advise to use a library (even JDBC) for security reasons, to prevent SQL injection attacks. For example: https://github.com/JetBrains/Exposed
👍 2
j
Theres no particular reason to use a library, as long as its ? you are adding. But also maybe don't need to build sql in coolest way, just simplest. If there are only 2 variants, could just type them in.....
👍 1
m
After many years of working with SQL in different languages, I would advise to stay away from manual query composition and let a robust lib do the job. If this is just for a personal project, to learn and experiment, then fine go for it.
👍 2
b
Copy code
fun <T> Iterable<T>.joinToSQLIn(separator: CharSequence = ",", prefix: CharSequence = "(", postfix: CharSequence = ")", limit: Int = -1, transform: ((T) -> CharSequence)? = { _ -> "?"}): String
        = this.joinToString(separator = separator, prefix = prefix, postfix = postfix, limit = limit, transform = transform)
then:
SELECT ${cols.joinToSQLIn()} ...
t
thank you all,,,,and thanks for the advice using sql framework
d
I tried Exposed and I was not a fan of it. I would suggest using another lib. Like kwery , kuery, ktorm
b