Database connection with Ktor(Kotlin)


In this blog, I will talk to you about a new framework in Ktor(Kotlin). if you don't know about Ktor you can watch my previous blog about Ktor-Click Here
In KTOR, You can connect with the database through Exposed library of Kotlin. So for the making of connection through the MySql database, you have to create a database.

1. I have created data as below SQL query.
After that, you have to create an empty KTOR project



 Now you can now try to connect through DB with help of Kotlin and expose library.
first of all, you have to add some line in build.gradle file to add expose and MySQL connector etc in your project inside dependency-

After that add these lines in the repository-

After that my final build.gradle file looks like below-

Then you can make an object of data table like below-

if you are from PHP MySQL background you can think what the fuck going on here but it's not as easy as in PHP.
In this blog, I will tell you about how to make a connection in JDBC driver the same as we do in java.
I am not using any external library like the connectionPool library in Spring framework of java.
Add below lines for connection here root is my database username and web is password-
now add below fun to fetch data In this I have written a DSL query and fetch records in form of ArrayList after that I converted it in JSON with GSON library -
after that create main fun to push data by HTTP protocol by the netty app engine.
after doing all of this my final Application.kt look like below-
Now you can make a connection with DB with the help of Ktor in Kotlin I will try to make a few more blogs in Kotlin Ktor to explore more to this framework and Language.
If you like this blog you can follow our blog for more awesome content.
To know more about how to create API in Ktor- ClickHere

                                           project code-CLICK HERE

Post a Comment

1 Comments