isc
isc

Reputation: 536

Connecting mySQL from Scala using JDBC driver

I need to connect to mySQL database from my Scala code. i have the below code to make the connection. i am importing the java packages to connect to database from scala and i am using the Drivermanager to make the connection. i have written one class and one method inside it for make the conection and i am extending and using it from my object.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;

class DBConnectionClass {
  val user = "root"
  val pass = "admin"
  val url = "jdbc:mysql://172.16.40.5/scalatest"
  def readDataBase() = {
   try {
        Class.forName("com.mysql.jdbc.Driver")
        val connection: Connection = DriverManager.getConnection(url, user, pass);

   } 
   catch {
      case _: Throwable => println("Could not connect to database")
  } 

}

}

and in my running scala object is,

 object TestAppMain {
 def main(args: Array[String]){
    val DBconnObject = new DBConnectionClass
    DBconnObject.readDataBase
    println("Check DB Is connected or not")
}
}

but it is throwing an exception that coud not connect to data base.. anybody can help me...thanx in advance

Upvotes: 2

Views: 2026

Answers (1)

duffymo
duffymo

Reputation: 308733

You'd be better off printing the stack trace instead of that message. The latter tells you something is wrong; the former tells you why.

I can only guess without the "why", but it could be the that JDBC driver JAR isn't available, the server isn't visible from the client, the MySQL listener isn't LISTENING on port 3306, there's a firewall between you and the server that doesn't allow you access.

Do you really want to log on as root? That seems dangerous and misguided to me.

Follow along carefully with this tutorial and you'll sort it out.

Upvotes: 2

Related Questions