2

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

1
  • Could you please tell us which exception precisely was thrown (the one you're catching inside DBConnectionClass)? Commented Mar 6, 2013 at 13:03

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.