直接上代码吧
package com.bigdata.test
import java.sql.{Connection, DriverManager, PreparedStatement}
import com.alibaba.fastjson.JSONObject
object TestApp {
private val url = "jdbc:mysql://localhost:3306/***?characterEncoding=UTF-8"
private val user = "****"
private val pwd = "****"
//scala 连接myql 并写一个demo数据到数据库表
def main(args: Array[String]): Unit = {
var connection:Connection = mysqlConncetion();
var jsonData:JSONObject = new JSONObject();
jsonData.put("id","123");
jsonData.put("name","456");
saveMysql(connection,jsonData);
}
def mysqlConncetion():Connection = {
DriverManager.getConnection(url,user,pwd);
}
def saveMysql(connection: Connection,jsonData: JSONObject):Unit={
var id = jsonData.getString("id");
val name = jsonData.getString("name");
var sql = s"insert into test_app(id,name) values(?,?)";
var ps:PreparedStatement = connection.prepareStatement(sql);
ps.setString(1,id);
ps.setString(2,name);
ps.execute();
}
}