Scala with JDBC connection and SQL SELECT

Category : Scala | Sub Category : Scala Programs | By Runner Dev Last updated: 2020-10-10 09:54:56 Viewed : 173


Scala with JDBC connection and SQL SELECT  

·        connecting to a MySQL database server on local computer

·        running a SQL SELECT query against the employee table of the mysql database 

Dependency:

download the jar : mysql-connector-java-5.1.49 

(OR)

MavenRepository:

<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->

<dependency>

    <groupId>mysql</groupId>

    <artifactId>mysql-connector-java</artifactId>

    <version>5.1.49</version>

</dependency>

Table Name: employee 

Columns Names:

            

Example:

Following example illustrates about Scala JDBC connection and SQL select

Query

Save the file as −  ScalaJdbcConnect.scala.  

ScalaJdbcConnect.scala  

 package runnerdev 

import java.sql.DriverManager

import java.sql.Connection 

object ScalaJdbcConnect { 

  def main(args: Array[String]) {

    // connect to the database named "test" on the localhost

    val driver = "com.mysql.jdbc.Driver"

    val url = "jdbc:mysql://localhost/test" //DB name test

    val username = "root"

    val password = "" 

    var connectionConnection = null 

    try {

      // make the connection

      Class.forName(driver)

      connection = DriverManager.getConnection(urlusernamepassword) 

      // create the statement, and run the select query

      val statement = connection.createStatement()

      val resultSet = statement.executeQuery("SELECT * FROM employee ")

      while (resultSet.next()) {

        val empId = resultSet.getString("empId")

        val empName = resultSet.getString("empName")

        val empAddr = resultSet.getString("empAddr")

 println("empId:" + empId + " empName " + empName + " empAddr: " + empAddr)

      }

    } catch {

      case e => e.printStackTrace

    } finally {

      connection.close()

    }

  } 

} 

compile and run the above example as follows 

scala> scalac ScalaJdbcConnect.scala

scalascala ScalaJdbcConnect 

Ouput:

empId:101

empName RamPrasad

empAddr: Bangalore

Search
Sub-Categories
Related Articles

Leave a Comment: