新しい言語触り始めた後にアプリつくろうと思うと、大体DB周り気になる。
ということでScalaからMySQLを触ってみたときのメモ。
今回はscalaqueryを使いました。
https://github.com/szeiger/scala-query
一応scala-dbcというのがscalaの標準ライブラリに入っているようなのですが、scala2.9.1でこいつを使うと、deprecatedのwarningに苛まれる事になります。
とりあえず2.9.1では使わないこと推奨?のようなので、Mavenでサクっとscalaquery入れた環境作りましょう。
使用するプロジェクトはmvn archetype:generateで適当にscalaのプロジェクトとして作成。
Mavenでscalaquery使うときは、
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | < dependencies > < dependency > < groupId >org.scalaquery</ groupId > < artifactId >scalaquery_2.8.1</ artifactId > < version >0.9.5</ version > </ dependency > </ dependencies > < repositories > < repository > < id >ScalaToolsMaven2Repository</ id > < name >Scala-Tools Maven2 Repository</ name > </ repository > </ repositories > |
をpom.xmlに追加しておいてください。
あと、mysqlのドライバもdependenciesの中に追記!
1 2 3 4 5 | < dependency > < groupId >mysql</ groupId > < artifactId >mysql-connector-java</ artifactId > < version >5.1.6</ version > </ dependency > |
そんでもってプロジェクトのフォルダで
1 | mvn scala:console |
を走らせると、必要なライブラリが入った状態のscalaコンソールが立ち上がります。
あとはこんな感じでmysqlと接続。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | scala> import org.scalaquery.session.Database import org.scalaquery.session.Database scala> import org.scalaquery.session.Database.threadLocalSession import org.scalaquery.session.Database.threadLocalSession scala> import org.scalaquery.simple.StaticQuery. _ import org.scalaquery.simple.StaticQuery. _ scala> val db = Database.forURL( "jdbc:mysql://localhost/test" ,driver = "com.mysql.jdbc.Driver" ,user = "hoge" ,password = "hoge" ) db : org.scalaquery.session.Database = org.scalaquery.session.Database$$anon$ 2 @ 3 c 10098 b scala> val select = queryNA[(Int,String)]( "select id,name from user" ) select : org.scalaquery.simple.StaticQuery[Unit,(Int, String)] with org.scalaquery.UnitInvokerMixin[(Int, String)] = org.scalaquery.simple.StaticQuery$$anon$ 1 @ 7 cc 3 feb 6 scala> db withSession{select.list} res 0 : List[(Int, String)] = List(( 1 ,y _ matsuwitter)) |
scalaqueryの詳しい使い方はまた調べて書きます。
では。
参考
http://scalaquery.org/download.html
http://d.hatena.ne.jp/tototoshi/20111119/1321677419