Scala with JDBC connection and SQL INSERT

Category : Scala | Sub Category : Scala Programs | By Runner Dev Last updated: 2020-10-10 10:03:49 Viewed : 176


Scala with JDBC connection and SQL INSERT 

·        connecting to a MySQL database server on   local computer

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

Save the file as −  ScalaJdbcInsert.scala.  

ScalaJdbcInsert.scala 

import java.sql.DriverManager

import java.sql.Connection 

object ScalaJdbcInsert {

  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 = "INSERT INTO employee " +

        "VALUES (102, `Sathya`, 4000, `Mumbai`)";

      val update = statement.executeUpdate(sql);

      println(update + " Record is  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 ScalaJdbcInsert.scala

C:>scala ScalaJdbcInsert 

Output:

1 Record is updated

empId:101

empName RamPrasad

empSal:20000

empAddr: Bangalore

empId:102

empName Sathya

empSal:4000

empAddr: Mumbai

Search
Sub-Categories
Related Articles

Leave a Comment: