课程表

Slick课程

工具箱
速查手册

Slick 使用SQL 语句

当前位置:免费教程 » 数据库/运维 » Slick

直接使用 SQL 语句

如果你有需要直接使用 SQL 语句,Slick 也支持你直接使用 SQL 语句。

首先你需要引入一些引用包:

  1. import scala.slick.jdbc.{GetResult, StaticQuery => Q}
  2. import scala.slick.jdbc.JdbcBackend.Database
  3. import Q.interpolation

其中最重要的一个相关类似 StaticQuery,为简洁起见,我们使用 Q 作为它的别名。

DDL 和 DML 语句

StaticQuery 的方法 updateNA,(NA 代表无参数),它返回 DDL 指令影响的行数,比如使用 H2 数据库

连接数据库:

  1. case class Supplier(id:Int, name:String, street:String, city:String, state:String, zip:String)
  2. case class Coffee(name:String, supID:Int, price:Double, sales:Int, total:Int)
  3. Database.forURL("jdbc:h2:mem:test1", driver = "org.h2.Driver") withDynSession {
  4. }

创建数据库表:

  1. // Create the tables, including primary and foreign keys
  2. Q.updateNA("create table suppliers("+
  3. "id int not null primary key, "+
  4. "name varchar not null, "+
  5. "street varchar not null, "+
  6. "city varchar not null, "+
  7. "state varchar not null, "+
  8. "zip varchar not null)").execute
  9. Q.updateNA("create table coffees("+
  10. "name varchar not null, "+
  11. "sup_id int not null, "+
  12. "price double not null, "+
  13. "sales int not null, "+
  14. "total int not null, "+
  15. "foreign key(sup_id) references suppliers(id))").execute

你可以使用字符串和一个 StaticQuery 对象相加(+)构成一个新的 StaticQuery 对象,一个简单的方法是使用 Q.u 和一个字符串相加,Q.u 代表一个相当与 StaticQuery.updateNA(“”)

例如我们在表中插入一些数据:

  1. // Insert some suppliers
  2. (Q.u + "insert into suppliers values(101, 'Acme, Inc.', '99 Market Street', 'Groundsville', 'CA', '95199')").execute
  3. (Q.u + "insert into suppliers values(49, 'Superior Coffee', '1 Party Place', 'Mendocino', 'CA', '95460')").execute
  4. (Q.u + "insert into suppliers values(150, 'The High Ground', '100 Coffee Lane', 'Meadows', 'CA', '93966')").execute

在 SQL 查询语句中使用字面量不是一种推荐的方法,尤其是当用户提供数据时(不十分安全), 此时你可以使用 +? 操作符为查询语句绑定一个参数,比如:

  1. def insert(c: Coffee) = (Q.u + "insert into coffees values (" +? c.name +
  2. "," +? c.supID + "," +? c.price + "," +? c.sales + "," +? c.total + ")").execute
  3. // Insert some coffees
  4. Seq(
  5. Coffee("Colombian", 101, 7.99, 0, 0),
  6. Coffee("French_Roast", 49, 8.99, 0, 0),
  7. Coffee("Espresso", 150, 9.99, 0, 0),
  8. Coffee("Colombian_Decaf", 101, 8.99, 0, 0),
  9. Coffee("French_Roast_Decaf", 49, 9.99, 0, 0)
  10. ).foreach(insert)

这段代码相对于 insert into coffees values (?,?,?,?,?)

查询语句

和 updateNA 类似, StaticQuery 还有一个 queryNA 方法,它支持一个类型参数(代表表的一行),比如:

  1. Q.queryNA[AlbumRow]("select * from Album") foreach { a =>
  2. println(" " + a.albumid + " " + a.title + " " + a.artistid)
  3. }

这段代码之所以能工作,是因为 Tables.scala 中定义了

  1. /** GetResult implicit for fetching AlbumRow objects using plain SQL queries */
  2. implicit def GetResultAlbumRow(implicit e0: GR[Int], e1: GR[String]): GR[AlbumRow] = GR{
  3. prs => import prs._
  4. AlbumRow.tupled((<<[Int], <<[String], <<[Int]))
  5. }

定义了从 JDBC 类型到 GetResult[T] 的隐含转换,GetResult[T] 为函数 PositionedResult => T 的一个封装。<<[T] 返回指定位置上期望的值。

和 queryNA 对应的带参数的 query 定义了两个类型参数,一个是参数的类型,另外一个是返回的结果的每行的类型,例如:

  1. val q2 = Q.query[Int,(Int,String,Int)] ( """
  2. select albumid,title,artistid from Album where artistid < ?
  3. """)
  4. val l2 = q2.list(10)
  5. for(t <- l2) println( " " + t._1 + " " + t._2 + " " + t._3)

返回结果如下:

  1. 1 For Those About To Rock We Salute You 1
  2. 4 Let There Be Rock 1
  3. 2 Balls to the Wall 2
  4. 3 Restless and Wild 2
  5. 5 Big Ones 3
  6. 6 Jagged Little Pill 4
  7. 7 Facelift 5
  8. 8 Warner 25 Anos 6
  9. 34 Chill: Brazil (Disc 2) 6
  10. 9 Plays Metallica By Four Cellos 7
  11. 10 Audioslave 8
  12. 11 Out Of Exile 8
  13. 271 Revelations 8
  14. 12 BackBeat Soundtrack 9

Q.interpolation 支持字符串插值,比如:

  1. def albumByTitle(title: String) = sql"select * from Album where title = $title".as[AlbumRow]
  2. println("Album: " + albumByTitle("Let There Be Rock").firstOption)

使用 sql 做为前缀的字符串,可以将以 $ 开始的变量替换成该变量的值,此外对于 update/delete 语句,可以使用 sqlu 前缀。

转载本站内容时,请务必注明来自W3xue,违者必究。
 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号