PreparedStatement 与StateMent 主要区别于 ps 是预编译,多次查询同样语法,但是参数不同的情况,只需要给?参数赋值即可,示例忽略try。
def transforDeviceId(): Unit = {
val url = "jdbc:mysql://localhost:3306/origin_platform"
val outPath = new File("e://testdata//output.txt")
var conn: Connection = null
var prepareStat: PreparedStatement = null
var rs: ResultSet = null
Class.forName("com.mysql.jdbc.Driver")
conn = DriverManager.getConnection(url, "root", "root")
// 处理完写出数据的位置
var fileWrite = new BufferedOutputStream(new FileOutputStream(outPath))
// 读取文件
val source = Source.fromFile("e://testdata//1569571348230.txt", "utf-8")
// 获取行
val lineIterator = source.getLines
var line = ""
var sqlStr = "select `device` from tb_device_map where `ID`= ?"
// 预编译
prepareStat = conn.prepareStatement(sqlStr)
while (lineIterator.hasNext) {
line = lineIterator.next()
// 将文件中 id_*数据匹配表中的 device_id,取出device,过滤 id_x,x只有1位,表示为空的情况
if (line.length > 4 && line.startsWith("id_")) {
// 给id赋值
prepareStat.setString(1, line.substring(3))
// 执行查询
rs = prepareStat.executeQuery
// 取出结果
if (rs.next) line = rs.getString(1)
fileWriter.write(line)
}
//不需要匹配的数据直接写入
fileWriter.write(line)
fileWriter.flush()
}
rs.close()
prepareStat.close()
conn.close()
}