Category : Scala | Sub Category : Scala Programs | By Prasad Bonam Last updated: 2020-10-10 05:02:06 Viewed : 9600
Scala with JDBC connection and SQL DELETE
·
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 DELETE
and SELECT query
Save the file as − ScalaJdbcDelete.scala
ScalaJdbcDelete.scala
package runnerdev
import java.sql.DriverManager
import java.sql.Connection
object ScalaJdbcDelete {
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 connection: Connection = null
try {
// make the connection
Class.forName(driver)
connection = DriverManager.getConnection(url, username, password)
// create the statement, and run the select query
val statement = connection.createStatement()
val sql = "DELETE FROM employee WHERE empId = 102";
val update = statement.executeUpdate(sql);
println(1 + " 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
ScalaJdbcDelete.scala
C:>scala ScalaJdbcDelete
Output:
1 Record is updated
empId:101
empName RamPrasad
empSal:5000
empAddr: Bangalore