当前位置:   article > 正文

通过jdbc连接Mysql并查询的步骤_jdbc查询mysql

jdbc查询mysql
从mysql中对表进行查询:
  1. Connection connection = null;
  2. PreparedStatement preparedStatement = null;
  3. ResultSet resultSet = null;
  4. try {
  5. // 1.注册驱动
  6. Class.forName("com.mysql.cj.jdbc.Driver");
  7. // 2.创建连接
  8. connection = DriverManager.getConnection(
  9. "jdbc:mysql://hadoop102:3306/gmall_realtime_config?" +
  10. "user=root&password=000000&useUnicode=true&" +
  11. "characterEncoding=utf8&serverTimeZone=Asia/Shanghai&useSSL=false");
  12. // 3.预编译sql,获取数据库操作对象
  13. preparedStatement = connection.prepareStatement(
  14. "select * from gmall_realtime_config.table_process where sink_type = 'dwd'");
  15. // 4.执行sql查询,获取数据集
  16. resultSet = preparedStatement.executeQuery();
  17. // 5.获取元数据信息
  18. ResultSetMetaData metaData = resultSet.getMetaData();
  19. // 6.处理查询结果。将查询信息 写入到 hashmap中
  20. while (resultSet.next()){
  21. JSONObject jsonObject = new JSONObject();
  22. for (int i = 1; i <= metaData.getColumnCount(); i++) {
  23. String columnName = metaData.getColumnName(i);
  24. String columnValue = resultSet.getString(i);
  25. jsonObject.put(columnName,columnValue);
  26. }
  27. TableProcess tableProcess = JSON.toJavaObject(jsonObject, TableProcess.class);
  28. if (tableProcess != null){
  29. String sourceTable = tableProcess.getSourceTable();
  30. String sourceType = tableProcess.getSourceType();
  31. String putKey = sourceTable + ":" + sourceType;
  32. hashMap.put(putKey,tableProcess);
  33. }
  34. }
  35. } catch (Exception e) {
  36. throw new RuntimeException(e);
  37. } finally {
  38.         // 7.关闭连接
  39. if (resultSet!= null) resultSet.close();
  40. if (preparedStatement != null) preparedStatement.close();
  41. if (connection != null) connection.close();
  42. }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/631476
推荐阅读
相关标签
  

闽ICP备14008679号