Scala with JDBC connection and SQL UPDATE

Category : Scala | Sub Category : Scala Programs | By Prasad Bonam Last updated: 2020-10-10 04:58:18 Viewed : 518


Scala with JDBC connection and SQL UPDATE 

·        connecting to a MySQL database server on local computer

·        running a SQL UPDATe and  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 UPDATE and SELECT query  

Save the file as −  ScalaJdbcUpdate.scala. 

 ScalaJdbcUpdate.scala  

  package runnerdev 

import java.sql.DriverManager

import java.sql.Connection 

object ScalaJdbcUpdate { 

  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 sql = "UPDATE employee " +

        "SET empSal = 5000 WHERE empId in (101, 102)";

      statement.executeUpdate(sql);

      val update = statement.executeUpdate(sql);

      println(update + " Record are  updated")

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

      while (resultSet.next()) {

        val empId = resultSet.getString("empId")

        val empName = resultSet.getString("empName")

        val empSal = resultSet.getString("empSal")

        val empAddr = resultSet.getString("empAddr")

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

      } 

    } catch {

      case e => { println("exception "e.printStackTrace) }

    } finally {

      connection.close()

    }

  } 

} 

 Compile and run the above example as follows −

C:>scalac ScalaJdbcUpdate.scala

C:>scala ScalaJdbcUpdate 

Output:

Output:

2 Record are  updated

empId:101

empName RamPrasad

empSal:5000

empAddr: Bangalore

empId:102

empName Sathya

empSal:5000

empAddr: Mumbai

Search
Related Articles

Leave a Comment: