赞
踩
- /**
- * scala连接mysql数据库
- */
- object JDBCDEmo8 {
- def main(args: Array[String]): Unit = {
- //加载驱动
- Class.forName("com.mysql.jdbc.Driver")
-
- //创建与数据库连接对象
- val conn: Connection = DriverManager.getConnection("jdbc:mysql://192.168.19.100/bigdata29?useUnicode=true&characterEncoding=utf8&useSSL=false", "root", "123456")
-
- //为了防止sql注入
- val state: PreparedStatement = conn.prepareStatement("select * from bigdata29.student where sage > ?")
- state.setString(1,"18")
-
- //执行sql语句
- val resultSet: ResultSet = state.executeQuery()
- while (resultSet.next()){
- val sno: String = resultSet.getString("sno")
- val sname: String = resultSet.getString("sname")
- val sgender: String = resultSet.getString("sgender")
- val sage: Int = resultSet.getInt("sage")
- val sclass: String = resultSet.getString("sclass")
- println(f"${sno},${sname},${sgender},${sage},${sclass}")
- }
- //释放资源
- state.close()
- conn.close()
- }
- }
- import com.alibaba.fastjson.{JSON, JSONArray, JSONObject}
- import scala.io.Source
-
- /**
- * 使用第三方的json解析工具:fastjson(fastjson是阿里很有名的json处理工具包) 或者 Gson(谷歌的)
- */
- object JsonDemp9 {
- def main(args: Array[String]): Unit = {
- val stuList1: List[String] = Source.fromFile("scala/data/stu2.json").getLines().toList
- val jsonStr: String = stuList1.mkString("\n")
-
-
- // //使用fastjson获取json对象
- // val jsonObject: JSONObject = JSON.parseObject(jsonStr)
- // //通过json对象使用键获取值
- // val name: String = jsonObject.getString("name")
- // println(name)
-
- //数据:[{"address":"安徽合肥","name":"张三","age":18},{"like":["踢足球","打篮球","举杠铃"],"name":"李四","age":18}]
- val jsonarray: JSONArray = JSON.parseArray(jsonStr)
- //通过索引获取数组中第二个json串
- val jSONObject: JSONObject = jsonarray.getJSONObject(1)
- println(jSONObject) //{"like":["踢足球","打篮球","举杠铃"],"name":"李四","age":18}
- val habbyValue: String = jSONObject.getString("like")
- println(habbyValue) //["踢足球","打篮球","举杠铃"]
- println("="*100)
-
-
- //遍历
- var index = 0
- while (index<jsonarray.size()){
- //通过索引下表获取每一个json串
- println(jsonarray.getJSONObject(index))
- index+=1
- }
-
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。