1. Create a Sparksql_mysql Scala object on idea.
2. The code to connect to MySQL is as follows
import java.sql. {DriverManager, PreparedStatement, Connection}import org.apache.spark.rdd.JdbcRDDimport Org.apache.spark. {sparkcontext, sparkconf}ObjectSparksql_mysql {def main (args:array[string]) {//connect to the database named "MySQL" on the localhostVal Driver ="Com.mysql.jdbc.Driver"val URL="jdbc:mysql://localhost:3306/test"val Username="Root"val Password="" //there ' s probably a better -to-do this varConnection:connection =NULL Try { //Make the connectionClass.forName (driver) connection=drivermanager.getconnection (URL, username, password)//Create the statement, and run the Select queryVal statement =connection.createstatement () Val insersql="INSERT into person (Person_id,first_name,last_name,gender) VALUES (6, ' Yuefei ', ' Zhang ', ' W ');"statement.executeupdate (Insersql) Val ResultSet= Statement.executequery ("SELECT first_name,last_name from person") while(Resultset.next ()) {Val first_name= Resultset.getstring ("first_name") Val last_name= Resultset.getstring ("last_name") println ("first_name, last_name ="+ first_name +", "+last_name)} println ("ResultSet", ResultSet)} Catch {//Case e = E.printstacktrace Case_: Throwable =println ("error come in ...")} connection.close ()}}
3. Description:
"com.mysql.jdbc.Driver" //specify MySQL dirver "jdbc:mysql://localhost:3306 /test//Specify MySQL address, test for database "root//specify MySQL username " " //password
Sparksql link MySQL