光滑:创建数据库

时间:2013-11-27 16:23:38

标签: scala slick

如果数据库尚不存在,是否有办法创建数据库?

Database.forURL("jdbc:mysql://127.0.0.1/database", driver = "com.mysql.jdbc.Driver", user = "root") withSession {
  // create tables, insert data
}

“数据库”不存在,所以我想光滑为我创建它。有任何想法吗?感谢。

2 个答案:

答案 0 :(得分:9)

您只能使用"jdbc:mysql://localhost/"作为JDBC URL连接到数据库引擎,然后发出纯SQL create database查询:

import scala.slick.driver.MySQLDriver.simple._
import scala.slick.jdbc.{StaticQuery => Q}

object Main extends App
{
    Database.forURL("jdbc:mysql://localhost/", driver = "com.mysql.jdbc.Driver") withSession {
        implicit session =>
            Q.updateNA("CREATE DATABASE `dataBaseName`").execute
        .
        .
        .
    }
}

答案 1 :(得分:9)

以上答案与Slick 2.x相关,其中withSession已被弃用, 这就是Slick 3.0.0 API的完成方式:

import scala.concurrent.Await
import scala.concurrent.duration._
import org.postgresql.util.PSQLException
import slick.driver.PostgresDriver
import slick.driver.PostgresDriver.api._

object SlickPGUtils {

  private val actionTimeout = 10 second
  private val driver = "org.postgresql.Driver"

  def createDb(host: String, port: Int, dbName: String, user: String, pwd: String) = {
    val onlyHostNoDbUrl = s"jdbc:postgresql://$host:$port/"
    using(Database.forURL(onlyHostNoDbUrl, user = user, password = pwd, driver = driver)) { conn =>
      Await.result(conn.run(sqlu"CREATE DATABASE #$dbName"), actionTimeout)
    }
  }

  def dropDb(host: String, port: Int, dbName: String, user: String, pwd: String) = {
    val onlyHostNoDbUrl = s"jdbc:postgresql://$host:$port/"
    try {
      using(Database.forURL(onlyHostNoDbUrl, user = user, password = pwd, driver = driver)) { conn =>
        Await.result(conn.run(sqlu"DROP DATABASE #$dbName"), actionTimeout)
      }
    } catch {
      // ignore failure due to db not exist
      case e:PSQLException => if (e.getMessage.equals(s""""database "$dbName" does not exist""")) {/* do nothing */}
      case e:Throwable => throw e // escalate other exceptions
    }
  }

  private def using[A <: {def close() : Unit}, B](resource: A)(f: A => B): B =
    try {
      f(resource)
    } finally {
      Try {
        resource.close()
      }.failed.foreach(err => throw new Exception(s"failed to close $resource", err))
    }
}