Table of contents
1.
Introduction💁
2.
Configuring JDBC Connection
3.
Configuring Driver Dependencies
4.
Database Configuration
4.1.
Changing the default name
4.2.
Configuring Several Data Sources
4.3.
Configuring SQLite database
4.4.
Configuring MySQL Database
4.5.
Configuring SQL Log Statement
5.
Accessing The JDBC Datasource
5.1.
Default Data Source
5.2.
Other Data Sources
6.
Creating a JDBC Connection
7.
Slick
7.1.
Slick Dependency
7.2.
JDBC Driver Dependency
7.3.
Database Configurations
7.4.
Accessing Database Using Slick
7.4.1.
For Default Data Source
7.4.2.
For Other Data Source
8.
Anorm
8.1.
Anorm Dependency
8.2.
Accessing Database
9.
Frequently Asked Questions
9.1.
What is JDBC?
9.2.
Who is a Scala Developer?
9.3.
Why are Scala Developers so well paid?
9.4.
Is Scala better than Java?
9.5.
What is the role of a Scala Developer?
10.
Conclusion
Last Updated: Mar 27, 2024
Medium

Scala Developers- Accessing a SQL Database

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction💁

Scala is a computer language for creating robust static systems and functional programs. It is JVM-based and object-oriented. It is capable of interacting with libraries and existing Java programs. The idea of primitive data is absent. Thus it is widely believed to be a static type of language.

Introduction

Configuring JDBC Connection

Before using the database in Scala, we need to configure and enable the SQL database plugins. To enable the database plugin in Scala, we can use the following code snippet,

libraryDependencies ++= Seq( jdbc )
JDBC

Configuring Driver Dependencies

JDBC does not provide any pre-defined drivers to handle the requests from the SQL database. Thus to use a database, you will need to add a new driver to handle the requests. For example, we can use the following code snippet to add a driver to handle a MySQL database of version 5.1.41,

libraryDependencies ++= Seq( "mysql" % "mysql-connector-java" % "5.1.41" )

Database Configuration

Now that we have configured the JDBC connection and also configured the Driver, we will now have to configure the SQL database. All the database configurations are made in a file named conf/application.conf. The default JDBC data source is called default, but the users may change it according to their convenience. The default configurations look something like this,

# Default configurations
db.default.driver = org.h2.Driver
db.default.url = "jdbc:h2:mem:play"

Changing the default name

As discussed earlier, users can also change the name of the default JDBC source. Users can use this code snippet to change the default name to CodingNinjas.

play.db.default = "CodingNinjas"
db.CodingNinjas.driver = org.h2.Driver
db.CodingNinjas.url = "jdbc:h2:mem:play"

Configuring Several Data Sources

We can configure several JDBC data sources using the following code snippet,

# Clients database
db.clients.driver=org.h2.Driver
db.clients.url="jdbc:h2:mem:clients"


# Company database
db.company.driver=org.h2.Driver
db.company.url="jdbc:h2:mem:company"

Configuring SQLite database

SQLite

We can also configure the  SQL database to use the SQLite engine connection properties. To configure the database to utilize the SQLite engine connection properties, we can use the following code snippet,

# Default database configuration using SQLite database engine
play.db.default = "CodingNinjas"
db.CodingNinjas.driver=org.sqlite.JDBC
db.CodingNinjas.url="jdbc:sqlite:(Path to the database file)"

Configuring MySQL Database

MySQL

We can also configure the SQL database to use the MySQL engine connection properties. To configure the  SQL database to utilize the MySQL engine connection properties, we can use the following code snippet,

# Default database configuration using MySQL database engine
play.db.default = "CodingNinjas"
db.CodingNinjas.driver = com.mysql.jdbc.Driver
db.CodingNinjas.url = "jdbc:mysql://localhost/newDB"
db.CodingNinjas.username = "MySQL username"
db.CodingNinjas.password = "MySQL Password"

Configuring SQL Log Statement

Not all the drivers offer a SQL log statement. So it is a good practice to explicitly enable the log statements in the configuration file. To enable the log statements, we can use the following code snippet,

# Enabling SQL Log Statements
play.db.default = "CodingNinjas"
db.CodingNinjas.driver=org.sqlite.JDBC
db.CodingNinjas.url="jdbc:sqlite:(Path to the database file)"
db.default.logSql=true

Accessing The JDBC Datasource

Default Data Source

Now that we have learned about the various configurations possible, let us talk about accessing the database. We can access the database using the following code snippet,

import javax.inject.Inject
import play.api.db.Database
import scala.concurrent.Future


class accessDefaultDataSource @Inject() (db: Database, databaseExecutionContext: DatabaseExecutionContext) {
  def updateSomething(): Unit = {
    Future {
      db.withConnection { conn =>
        // Perform CRUD operations here
      } // Connection terminates here
    }(databaseExecutionContext)
  }
}

Other Data Sources

In case we are not using the default data source, we will need to make in few tweaks in the above code,

import javax.inject.Inject
import play.api.db.Database
import play.db.NamedDatabase


import scala.concurrent.Future


class accessOtherDataSource @Inject() ( @NamedDatabase("clients") cliebtsDatabase: Database, databaseExecutionContext: DatabaseExecutionContext ) {
  def updateSomething(): Unit = {
    Future {
      ordersDatabase.withConnection { conn =>
        // Perform your CRUD operations here
      } // Connection terminates here
    }(databaseExecutionContext)
  }
}

Creating a JDBC Connection

Now that we have the necessary drivers and the data source, we can also create a JDBC connection using the following code snippet,

import javax.inject.Inject
import play.api.db.Database


import scala.concurrent.Future

class createJdbcConnection @Inject() (db: Database, databaseExecutionContext: DatabaseExecutionContext) {
  def updateSomething(): Unit = {
    Future {
      // creating a jdbc connection
      val connection = db.getConnection()
      // perform your CRUD actions here
      // ending the jdbc connection
      connection.close()
    }(databaseExecutionContext)
  }
}

Slick

Slick is used to efficiently access the databases. Using Slick has two major advantages,

  • Slick provides support for Play Database evolutions.
     
  • Integration of Slick into the lifecycle of the Play’s application.
Slick

Slick Dependency

Before we can start using Slick, we need to add the following dependency.

libraryDependencies += "com.typesafe.play" %% "play-slick" % "5.0.0"

JDBC Driver Dependency

If we are using Slick, we need to explicitly add the JDBC driver dependency. We can add the JDBC driver dependency using the following code snippet,

libraryDependencies += "com.h2database" % "h2" % "1.4.200"

Database Configurations

Before we can enable accessing the database using Slick, we will need to add some database configurations in the application.conf file. We need to add the following configurations,

#Database configuration for Slick
slick.dbs.default.profile="slick.jdbc.H2Profile$"
slick.dbs.default.db.driver="org.h2.Driver"
slick.dbs.default.db.url="jdbc:h2:mem:play"

 

We can also add multiple database configurations using the following code snippet,

#Adding Multiple Database Configurations


# Clients database
slick.dbs.clients.profile="slick.jdbc.H2Profile$"
slick.dbs.clients.db.driver="org.h2.Driver"
slick.dbs.clients.db.url="jdbc:h2:mem:play"


# Company database
slick.dbs.company.profile="slick.jdbc.H2Profile$"
slick.dbs.company.db.driver="org.h2.Driver"
slick.dbs.company.db.url="jdbc:h2:mem:play"

Accessing Database Using Slick

For Default Data Source

We can use the following code snippet to declare a class to access the Database for the default data source,

class SlickDefaultDataSource @Inject() (protected val dbConfigProvider: DatabaseConfigProvider, cc: ControllerComponents)( implicit ec: ExecutionContext ) extends AbstractController(cc) with HasDatabaseConfigProvider[JdbcProfile]

For Other Data Source

We can use the following code snippet to declare a class to access the Database for other data sources,

class SlickOtherDataSource @Inject() ( @NamedDatabase("Your DB Name Here") protected val dbConfigProvider: DatabaseConfigProvider, cc: ControllerComponents )(implicit ec: ExecutionContext) extends AbstractController(cc) with HasDatabaseConfigProvider[JdbcProfile]

Anorm

As we can clearly see, using plain JDBC can be quite tiring as it requires writing huge codes just to create a simple connection with the database. Anorm is a simple JDBC API that reduces code redundancy and helps developers write smaller and faster codes. Some of the advantages of using Anorm are,

  • It makes it easier to write JDBC codes.
     
  • There is no need for another DSL(Domain Specific Language) to access relational databases.
     
  • Anorm provides better control over your SQL code.

Anorm Dependency

Before we can start using Anorm, we need to add the following dependency.

libraryDependencies ++= Seq( jdbc, "org.playframework.anorm" %% "anorm" % "2.6.10" )

Accessing Database

Accessing a database is quite simple with the Anorm API. Users can simply use the following code snippet to insert values into an existing table,

//fetching the Anorm API using the import keyword
import anorm
val id: Option[Long] =  SQL("insert into item(name, value) values ({name}, {value})") .on("name" -> "Pencil", "country" -> "₹10").executeInsert()

As the above code shows, Anorm makes handling databases very easy. Users can import the Anorm API into their code and start using the Anorm API directly.

 

Now let's discuss some frequently asked questions associated with Scala Developers- Accessing a SQL Database.

FAQs

Frequently Asked Questions

What is JDBC?

JDBC stands for Java Database Connectivity. JDBC is a programming interface for Java that defines how a user can access to connect to a database using Java.

Who is a Scala Developer?

A Scala Developer is a person who has a high-level understanding of creating, maintaining and designing Scala Based Applications. 

Why are Scala Developers so well paid?

Scala is regarded as an emerging ability, which has seen a significant increase in demand over the previous five years. Thus there is a huge demand for Scala Developers in the industry.

Is Scala better than Java?

According to the study, Scala is quicker than Java. Typical developers can write code without too much thought given to optimization. Thus it can be concluded that Scala is better than Java.

What is the role of a Scala Developer?

Since clicking refresh is not counted as a time-out scenario, so as soon as the reload button is pressed, this causes the existing subclass objects to be replaced with new subclass objects. Thus there might rise a need to preserve the content on hitting refresh.

Conclusion

In this article, we discussed all about accessing a SQL database. We also discussed the various ways of accessing a SQL database. 

Hey Ninjas! Don’t stop here. Check out Coding Ninjas for Python, more unique courses, and guided paths. Also, check out our courses on DSA, and OOPS. Also, try Coding Ninjas Studio for more exciting articles, interview experiences, and excellent Machine Learning and Python problems. 

Live masterclass