Scala database operations

Source: Internet
Author: User

Scala's framework for various database operations has come out, for example: Scalaquery, O/R Broker, Squeryl, and so on. However, the Scala programming book I read never had a section on database operations, so I was curious to find some information and eventually wrote a simple Scala-based database operation code. 1. Connect to the database

And Java is not much different, or to define the database four a few parameters, the operation steps and JDBC as the same. The only thing to note is that Class.forName () in JDBC is replaced with Classof[com.mysql.jdbc.driver], and "Com.mysql.jdbc.Driver" is not quoted .

Gossip less, look at the code directly below it.

Package Edu.wzm.db.scala Import java.sql.Connection import Java.sql.DriverManager//import java.sql.PreparedStatement
 Import Java.sql.ResultSet/** * Created by Gatsbynewton on 2015/10/12. */object dbutils {val url = "Jdbc:mysql://localhost:3306/test" val username = "root" val Password = "Admin" cl Assof[com.mysql.jdbc.driver] def getconnection (): Connection = {drivermanager.getconnection (URL, username, passwor
      d)} def close (conn:connection): Unit = {try{if (!conn.isclosed () | | Conn! = NULL) {Conn.close () }} catch {case ex:exception + = {ex.printstacktrace ()}}}/Def close (R    S:resultset): Unit = {//try {//if (!rs.isclosed () | | | rs! = NULL) {//Rs.close ()//}//}// catch {//case ex:exception + = {//Ex.printstacktrace ()//}//}//}////Def close (pstm: PreparedStatement): Unit = {//try {//if (!pstm.isclosed () | | pSTM = null) {//Pstm.close ()//}//}//Catch {//case ex:exception + =//Ex.print StackTrace ()//}//}//}}
After reading the code, a small partner may ask "why ResultSet and PreparedStatement's close code is commented out" and the reason is found in the following acid operation.

2.ACID Operation

Package Edu.wzm.db.scala Import scala.collection.mutable import scala.collection.mutable.ArrayBuffer/** * Created by G
 Atsbynewton on 2015/10/12. */class Operators {case Class User (id:string, name:string, Age:int)//insert operator def Add (user:user): Bo  Olean = {Val conn = dbutils.getconnection () try{val sql = new StringBuilder (). Append ("INSERT into
      User (ID, name, age). Append ("VALUES (?,?,?)")
      Val pstm = conn.preparestatement (sql.tostring ()) Pstm.setobject (1, user.id) Pstm.setobject (2, User.Name) Pstm.setobject (3, User.age) pstm.executeupdate () > 0} finally {Conn.close ()}}//dele Te operator def delete (id:string): Boolean ={val conn = dbutils.getconnection () try{val sql = "Delete F
      ROM user WHERE id =? "
      Val pstm = conn.preparestatement (sql) Pstm.setobject (1, id) pstm.executeupdate () > 0} finally { Dbutils.close (cOnn)}}//update operator def modify (user:user): Boolean ={val conn = dbutils.getconnection () try{ Val sql = "UPDATE user SET age =?"
      WHERE id =? " Val pstm = conn.preparestatement (sql) Pstm.setobject (1, User.age) Pstm.setobject (2, User.ID) PSTM.EXECU Teupdate () > 0} finally {dbutils.close (conn)}}//select operator def query (id:int): Array Buffer[mutable. Hashmap[string, any]] = {Val conn = dbutils.getconnection () try{val sql = new StringBuilder (). App
      End ("Select name, Age"). Append ("from user"). Append ("WHERE ID >?")  Val pstm = conn.preparestatement (sql.tostring ()) Pstm.setobject (1, id) Val rs = Pstm.executequery () val RSMD = Rs.getmetadata () val size = Rsmd.getcolumncount () val buffer = new arraybuffer[mutable. Hashmap[string, any] [] () while (Rs.next ()) {val map = mutable. Hashmap[string, any] () for (I <-1 to size) {map + = (Rsmd.getcolumnlabel (i), rs.getstring (i))} buffer + = map } buffer} finally {Conn.close ()}}}
After reading the code, you will find that the JavaBean in JDBC is replaced by the Scala case class. In addition, the bulk delete code I did not write, basically and JDBC in the bulk delete no difference.

In short, Scala calls the Java API when it comes to database operations, and from here you can see the seamless integration of Scala and Java. I think this may be why the Scala programming book does not have the content of the relevant database operation.


The complete code (with MySQL data) I have hosted on GitHub, and the source code contains the JDBC code, which can be compared.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.