依赖::::
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>6.4.0.jre8</version>
</dependency>
<dependency>
<groupId>org.scalikejdbc</groupId>
<artifactId>scalikejdbc-core_2.11</artifactId>
<version>2.5.0</version>
</dependency>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<scala.version>2.11.8</scala.version>
<spark.version>2.1.1</spark.version>
<hadoop.version>2.8.3</hadoop.version>
<encoding>UTF-8</encoding>
</properties>
<dependencies>
<!-- 导入scala的依赖 -->
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
<version>${scala.version}</version>
</dependency>
===============链接数据库=======================
val url = "jdbc:sqlserver://ip;DatabaseName=数据库名字"
//驱动名称
val driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver"
//用户名
val username = "root"
//密码
val password = "root"
//初始化数据连接
var connection: Connection = null
try {
//注册Driver
Class.forName(driver)
//得到连接
connection = DriverManager.getConnection(url, username, password)
println("连接上了!")
val statement = connection.createStatement //(创建状态)
====================执行查询SQL=========================
val rs_v_PO_AEAPV = statement.executeQuery(" select ID,name,age from Table")
得到一个结果集=>ResultSet
===================操作结果集ResultSet=====================
对结果集进行while循环 rs.next()
获得数据表中的字段 :val YearMonth = rs.getInt("ID")
把字段添加到list集合中,
(对集合进行类操作case class tt( ID:Int,name:String))
=====================操作list集合存储csv文件中==============
最重要的一点***********
创建打印字符流/输出流
val writer = new PrintWriter("v_Line.csv")
再对list进行for循环
for (i <- list) {
writer.print(i.ID+",")
writer.print(i.name+",")//用print 加上“,”
writer.println(i.age) //最后用println
}
关闭流
writer .close