spark任务连接mysql

spark任务连接mysql,第1张

spark任务连接mysql

mysql 连接:

首先确认mysql的版本:执行查询语句

select version();

maven中配置mysql连接:

        
            mysql
            mysql-connector-java
            8.0.21
        

版本最好与mysql版本保持一致,避免出现一些奇怪的问题

获取mysql连接:

   //驱动
   static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        }catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    //获取连接
    public static Connection getMysqlConnection(String url,String userName,String password) throws SQLException {
        Connection connection = DriverManager.getConnection(url,userName,password);
        return connection;
    }

spark任务提交:

spark2-submit 
--master yarn 
--deploy-mode cluster 
--class cn.xxx.SparkToMysql 
--conf spark.yarn.maxAppAttempts=1 
--driver-class-path mysql-connector-java-8.0.21.jar 
SparkTest.jar 

记得将mysql驱动包上传,

常见报错:

Unregistering ApplicationMaster with FAILED (diag message: User class threw exception: java.sql.SQLException: No suitable driver found for jdbc:mysql:

一般是由于没有将驱动包上传,或者spark任务提交的时候 没有配置 --driver-class-path

或者没有 写 Class.forName("com.mysql.jdbc.Driver");

其他方式连接

    public static Dataset executeSql(SparkSession sparkSession, String url,String userName,String password, String sql) {
        String table = "(" + sql + ") AS MYSQL_TABLE";
        Map options = new HashMap<>();
        options.put("url",url);
        options.put("driver","com.mysql.jdbc.Driver");
        options.put("user", userName);
        options.put("password", password);
        options.put("dbtable", table);
        return sparkSession.sqlContext().read().format("jdbc").options(options).load();
    }

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5664969.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存