DataBaseHelper.java 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package com.ruoyi.common.helper;
  2. import cn.hutool.core.convert.Convert;
  3. import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
  4. import com.ruoyi.common.enums.DataBaseType;
  5. import com.ruoyi.common.exception.ServiceException;
  6. import com.ruoyi.common.utils.spring.SpringUtils;
  7. import lombok.AccessLevel;
  8. import lombok.NoArgsConstructor;
  9. import javax.sql.DataSource;
  10. import java.sql.DatabaseMetaData;
  11. import java.sql.SQLException;
  12. /**
  13. * 数据库助手
  14. *
  15. * @author Lion Li
  16. */
  17. @NoArgsConstructor(access = AccessLevel.PRIVATE)
  18. public class DataBaseHelper {
  19. /**
  20. * 获取当前数据库类型
  21. */
  22. public static DataBaseType getDataBasyType() {
  23. DynamicRoutingDataSource ds = (DynamicRoutingDataSource) SpringUtils.getBean(DataSource.class);
  24. DataSource dataSource = ds.determineDataSource();
  25. try {
  26. DatabaseMetaData metaData = dataSource.getConnection().getMetaData();
  27. String databaseProductName = metaData.getDatabaseProductName();
  28. return DataBaseType.find(databaseProductName);
  29. } catch (SQLException e) {
  30. throw new ServiceException(e.getMessage());
  31. }
  32. }
  33. public static boolean isMySql() {
  34. return DataBaseType.MY_SQL == getDataBasyType();
  35. }
  36. public static boolean isOracle() {
  37. return DataBaseType.ORACLE == getDataBasyType();
  38. }
  39. public static boolean isPostgerSql() {
  40. return DataBaseType.POSTGRE_SQL == getDataBasyType();
  41. }
  42. public static boolean isSqlServer() {
  43. return DataBaseType.SQL_SERVER == getDataBasyType();
  44. }
  45. public static String findInSet(Object var1, String var2) {
  46. DataBaseType dataBasyType = getDataBasyType();
  47. String var = Convert.toStr(var1);
  48. if (dataBasyType == DataBaseType.SQL_SERVER) {
  49. // charindex(',100,' , ',0,100,101,') <> 0
  50. return "charindex('," + var + ",' , ','+" + var2 + "+',') <> 0";
  51. } else if (dataBasyType == DataBaseType.POSTGRE_SQL) {
  52. // (select position(',100,' in ',0,100,101,')) <> 0
  53. return "(select position('," + var + ",' in ','||" + var2 + "||',')) <> 0";
  54. } else if (dataBasyType == DataBaseType.ORACLE) {
  55. // instr(',0,100,101,' , ',100,') <> 0
  56. return "instr(','||" + var2 + "||',' , '," + var + ",') <> 0";
  57. }
  58. // find_in_set(100 , '0,100,101')
  59. return "find_in_set(" + var + " , " + var2 + ") <> 0";
  60. }
  61. }