方法一:链接并操作mysql
//链接Mysql
val driver = "com.mysql.jdbc.Driver"
val url = "jdbc:mysql://10.1.2.190:8066/mq_sale_disc"
val username = "kr.user"
val password = "user@85263382"
var connectionMqcrm: Connection = null
Class.forName(driver)
connectionMqcrm = DriverManager.getConnection(url, username, password)
val statement = connectionMqcrm.createStatement()
//查询、插入
var count = 0
val sqlname = "insert into tmp_enterprise( ENTERPRISE_NAME ) values (\'" + coname + "\') "
val sqlcount = "select count(*) from tmp_enterprise where ENTERPRISE_NAME =\'" + coname + "\' "
var ecusqlcount = statement.executeQuery(sqlcount)
while (ecusqlcount.next()){
count = ecusqlcount.getInt(1)
}
if (count >0) {
val ecusqlname = statement.executeUpdate(sqlname)
}
//插入征信分数
var countnum =0
var companyID = 0
val sqlID = "select ENTERPRISE_ID from tmp_enterprise where ENTERPRISE_NAME= \'" + coname +"\' "
val ecusqlID = statement.executeQuery(sqlID)
while (ecusqlID.next()){
companyID = ecusqlID.getInt("ENTERPRISE_ID")
}
val timenew = System.currentTimeMillis()
var dateFormat: SimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd")
var nowtime: Date = new Date(timenew)
val currentTimenew = dateFormat.format(nowtime)
val sqlscore = "insert into tm_enterprise_credit(CREATE_TIME ,UPDATE_TIME , ENTERPRISE_ID, CREDIT_SCORE ) values( \'" + currentTimenew + "\' , \'" + currentTimenew + "\',\'" + companyID + "\',\'" + score + "\')"
val sqlcountN = "select count(*) from tm_enterprise_credit where ENTERPRISE_ID = \'" + companyID + "\'"
val ecusqlcountN = statement.executeQuery(sqlcountN)
while (ecusqlcountN.next()){
countnum = ecusqlcountN.getInt(1)
}
if (countnum > 0 ) {
val sqlnew = "update tm_enterprise_credit set CREDIT_SCORE= \'" + score + " \' , UPDATE_TIME= \'" + currentTimenew + "\'" + "where ENTERPRISE_ID= \'" + companyID + "\'"
val ecusqlnew = statement.executeUpdate(sqlnew)
} else {
val ecusqlscore = statement.executeUpdate(sqlscore)
}
方法二:查询
val jdbcDF = sqlContext.read.format("jdbc").options(Map("url" -> "jdbc:mysql://10.1.2.190:8066/mq_crm?user=kr.user&password=user@85263382",
"dbtable" -> "crm_order")).load()
val tableDF = sqlContext.jdbc("jdbc:mysql://mysql_hostname:mysql_port/testDF?user=your_username&password=your_password", "user")
//查询mySql数据库
val tableDF = sqlContext.jdbc("jdbc:mysql://10.1.2.190:8066/mq_sale_disc?user=kr.user&password=user@85263382", "tmp_enterprise")
注意:execute、executeUpdate、executeQuery三者区别
查询用executeQuery
插入、更新、删除用executeUpdate