利用SQL处理CVS文件:CSVQuery

jopen 10年前

CSVQuery是一个用于处理CVS文件的便利 SQL Runner。你可以使用SQL来解析和过滤CSV行。

import scalikejdbc._  import csvquery._  implicit val session = autoCSVSession    // ---  // simple queries    val csv = CSV("./sample.csv", Seq("name", "age"))    val count: Long = withCSV(csv) { table =>    sql"select count(*) from $table".map(_.long(1)).single.apply().get  }    val records: Seq[Map[String, Any]] = withCSV(csv) { table =>    sql"select * from $table".toMap.list.apply()  }    // ---  // join queries    case class Account(name: String, companyName: String, company: Option[Company])  case class Company(name: String, url: String)    val (accountsCsv, companiesCsv) = (    CSV("src/test/resources/accounts.csv", Seq("name", "company_name")),    CSV("src/test/resources/companies.csv", Seq("name", "url"))  )  val accounts: Seq[Account] = withCSV(accountsCsv, companiesCsv) { (a, c) =>    sql"select a.name, a.company_name, c.url from $a a left join $c c on a.company_name = c.name".map { rs =>      new Account(        name = rs.get("name"),        companyName = rs.get("company_name"),        company = rs.stringOpt("url").map(url => Company(rs.get("company_name"), url))      )    }.list.apply()  }    // ---  // SkinnyCSVMapper examples  // also required: "org.skinny-framework" %% "skinny-orm"  // NOTICE: Compilation of DAO definitio on the REPL fails, use initialCommands instead.    case class User(name: String, age: Int)  object UserDAO extends SkinnyCSVMapper[User] {    def csv = CSV("./sample.csv", Seq("name", "age"))    override def extract(rs: WrappedResultSet, rn: ResultName[User]) = autoConstruct(rs, rn)  }  val users = UserDAO.findAll()  val alice = UserDAO.where('name -> "Alice").apply().headOption

项目主页:http://www.open-open.com/lib/view/home/1414051908419