본문 바로가기
MySql

MySQL SBT Scala 프로젝트에서 MySQL JDBC 드라이버를 사용하는 방법은 무엇입니까?

by 베이스 공부 2020. 11. 3.
반응형

SBT 세션 중에 처음으로 프로젝트를 실행하면 MySQL 데이터베이스에 액세스하려고 할 때 다음 예외가 발생합니다.

java.lang.NoClassDefFoundError : scala / Ordered

다시 실행하면 (그리고 그 이후에 동일한 SBT 세션 동안) 다른 것을 던집니다.

java.sql.SQLException : jdbc : mysql : // localhost / ...에 적합한 드라이버가 없습니다.

NetBeans를 사용할 때 동일한 코드가 정상적으로 작동했습니다. 이제 SBT를 사용하여 빌드하고 Kate를 사용하여 프로젝트를 수동으로 편집하고 관리 할 때 이러한 런타임 오류가 발생합니다.

MySQL JDBC 드라이버 (MySQL.com에서 바로 다운로드) JAR은 프로젝트의 lib 디렉토리에 있으며 내가 거기에 넣은 다른 모든 라이브러리는 정상적으로 작동합니다.

다음은 코드입니다.

import java.sql._
...
// read
val dbc : Connection = DriverManager.getConnection("jdbc:mysql://localhost/...")
val st : Statement = dbc.createStatement
val rs : ResultSet = st.executeQuery("SELECT ...")
if(rs.first) result = rs.getDouble("field")
dbc.close
...
// write
val dbc : Connection = DriverManager.getConnection("jdbc:mysql://localhost/...")
val st : Statement = dbc.createStatement
st.execute("UPDATE ...")
dbc.close


 

해결 방법

 

SBT 프로젝트 클래스에는 다음 줄이 있어야합니다.

 // Declare MySQL connector Dependency
  val mysql = "mysql" % "mysql-connector-java" % "5.1.12"

MySQL 용 JDBC 드라이버 JAR 파일을 가져옵니다.

드라이버를로드 했습니까? 이 Util 클래스를 사용하여 연결을 가져 오면 드라이버가 정확히 한 번로드됩니다.

// Util Class
object DaoUtil {
  import java.sql.{DriverManager, Connection}

  private var driverLoaded = false

  private def loadDriver()  {
    try{
      Class.forName("com.mysql.jdbc.Driver").newInstance
      driverLoaded = true
    }catch{
      case e: Exception  => {
        println("ERROR: Driver not available: " + e.getMessage)
        throw e
      }
    }
  }

  def getConnection(dbc: DbConnection): Connection =  {
    // Only load driver first time
    this.synchronized {
      if(! driverLoaded) loadDriver()
    }

    // Get the connection
    try{
      DriverManager.getConnection(dbc.getConnectionString)
    }catch{
      case e: Exception  => {
        println("ERROR: No connection: " + e.getMessage)
        throw e
      }
    }
  }
}


 

참조 페이지 https://stackoverflow.com/questions/3896153

 

 

반응형

댓글