将光滑的3.1.1连接到数据库

时间:2016-06-06 11:53:04

标签: scala slick

我有以下代码,并且我试图连接到MySQL数据库但没有成功。

cat Database.scala

package com.github.odnanref.EmailFilter

import slick.driver.MySQLDriver._
import slick.driver.MySQLDriver.backend.Database

/**
  * Created by andref on 12/05/16.
  */
class Database {
  val url = "jdbc:mysql://localhost/playdb"
  val db = Database.forURL(url, driver = "com.mysql.jdbc.Driver")

  override def finalize() {
    db.close()

    super.finalize()
  }
}

cat EmailMessageTable.scala

package com.github.odnanref.EmailFilter

import java.sql.Timestamp

import slick.driver.JdbcProfile
import slick.driver.MySQLDriver.api._

import scala.concurrent.Future

class EmailMessageTable(tag: Tag) extends Table[EmailMessage](tag, "email_message") {

  def id      = column[Option[Long]]("id", O.AutoInc, O.PrimaryKey)
  def email   = column[String]("email")
  def subject = column[String]("subject")
  def body    = column[String]("body")
  def datain  = column[Timestamp]("datain")
  def email_id= column[Long]("email_id")

  def * = (id, email, subject, body, datain, email_id) <> ((EmailMessage.apply _).tupled, EmailMessage.unapply)
  def ? = (id.get.?, email.?, subject.?, body.?, datain.?).shaped.<>({ r =>; _1.map(_ =>
    EmailMessage.tupled((_1, _2.get, _3.get, _4.get, _5.get))) }, (_: Any) =>
    throw new Exception("Inserting into ? projection not supported."))
}

我无法初始化数据库并根据我尝试的代码执行搜索查询或插入语句

val db = new Database()
db.db.run(TableQuery[EmailMessageTable] += EmailMessage(...) )
And it says, it doesn't know the method +=

我也收到此错误:

Database.scala:4: imported `Database' is permanently hidden by definition of class Database in package EmailFilter
[warn] import slick.driver.MySQLDriver.backend.Database

我做错了什么?

发布编辑&gt;

package com.github.odnanref.EmailFilter

import java.sql.Timestamp


case class EmailMessage(
  id: Option[Long], 
  email: String, 
  subject:String,
  body:String,
  datain: Timestamp,
  email_id: Long
)

1 个答案:

答案 0 :(得分:1)

您正在一个文件中导入一个名为Database的类,该文件定义了另一个具有相同名称的类。你可以:

  • 重命名您的Database班级:

    class MyDatabase {
     val url = ...
     val db = ...
     ...
    }
    
  • 重命名导入的类:

    import slick.driver.MySQLDriver.backend.{Database => SlickDB}
    ...
    val db = SlickDB.forURL(url, driver = "com.mysql.jdbc.Driver")
    
  • 避免明确导入Database

    import slick.driver.MySQLDriver.backend
    ...
    val db = backend.Database.forURL(url, driver = "com.mysql.jdbc.Driver")