Java Code Examples for java.sql.DatabaseMetaData#getDatabaseProductName()

The following examples show how to use java.sql.DatabaseMetaData#getDatabaseProductName() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DialectFactoryBean.java    From spring-data-mybatis with Apache License 2.0 7 votes vote down vote up
private Dialect getDialect(DatabaseMetaData metaData) throws SQLException {
	final String databaseName = metaData.getDatabaseProductName();
	final int majorVersion = interpretVersion(metaData.getDatabaseMajorVersion());
	final int minorVersion = interpretVersion(metaData.getDatabaseMinorVersion());

	if ("H2".equalsIgnoreCase(databaseName)) {
		return new H2Dialect();
	}
	if ("MySQL".equalsIgnoreCase(databaseName)) {
		return new MySQLDialect();
	}
	// if (databaseName.startsWith("Microsoft SQL Server")) {
	// return new SqlServer2012Dialect();
	// }
	// if ("Oracle".equalsIgnoreCase(databaseName)) {
	// return new OracleDialect();
	// }
	// if ("PostgreSQL".equalsIgnoreCase(databaseName)) {
	// return new PostgreSQLDialect();
	// }
	// return new AnsiSqlDialect();
	return null;
}
 
Example 2
Source File: DbUtilities.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
public static boolean checkDbVendorIsMariaDB(Connection connection) {
	if (connection == null) {
		throw new RuntimeException("Cannot detect db vendor: connection is null");
	}

	try {
		DatabaseMetaData databaseMetaData = connection.getMetaData();
		if (databaseMetaData != null) {
			String productName = databaseMetaData.getDatabaseProductName();
			if ("maria".equalsIgnoreCase(productName)
					|| "mariadb".equalsIgnoreCase(productName)
					|| databaseMetaData.getURL().toLowerCase().startsWith("jdbc:mariadb:")) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	} catch (Exception e) {
		logger.error("Cannot detect db vendor: " + e.getMessage(), e);
		throw new RuntimeException("Cannot detect db vendor: " + e.getMessage(), e);
	}
}
 
Example 3
Source File: AceQLMetaDataTestDatabaseMetaData.java    From aceql-http with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
    * @param args
    */
   public static void main(String[] args) throws Exception {

for (int i = 1; i < 6; i++) {
    Connection connection = ConnectionParms.getConnection(i);

    DatabaseMetaData databaseMetaData = connection.getMetaData();
    String databaseProductName = databaseMetaData.getDatabaseProductName();
    System.out.println();
    System.out.println("Product : " + databaseProductName);
    System.out.println("UserName: " + databaseMetaData.getUserName());

    AceQLMetaData aceQLMetaData = new AceQLMetaData(connection);
    JdbcDatabaseMetaData jdbcDatabaseMetaData = aceQLMetaData.getJdbcDatabaseMetaData();

    System.out.println("jdbcDatabaseMetaData  : " + jdbcDatabaseMetaData);
}

   }
 
Example 4
Source File: AbstractDialect.java    From bdf3 with Apache License 2.0 6 votes vote down vote up
/**
 * 判断是否是支持的数据库类型
 * @param connection 数据连接
 * @param dbProductName 数据库名称
 * @param dbMajorVersion 数据版本号
 * @return 返回当前方言是否支持当前数据库
 */
public boolean support(Connection connection,String dbProductName,String dbMajorVersion) {
	try {
		DatabaseMetaData databaseMetaData = connection.getMetaData();
		String databaseProductName = databaseMetaData
				.getDatabaseProductName();
		int databaseMajorVersion = databaseMetaData
		.getDatabaseMajorVersion();
		boolean containsMysql = StringUtils.containsIgnoreCase(
				databaseProductName,dbProductName);
		if(StringUtils.isNotEmpty(dbMajorVersion)){
			return containsMysql&&Integer.valueOf(dbMajorVersion)==databaseMajorVersion;
		}
		return containsMysql;
	} catch (SQLException e) {
		return false;
	}
}
 
Example 5
Source File: TradeJEEDirect.java    From jboss-daytrader with Apache License 2.0 6 votes vote down vote up
public String checkDBProductName() throws Exception {
    Connection conn = null;
    String dbProductName = null;

    try {
        if (Log.doTrace())
            Log.traceEnter("TradeDirect:checkDBProductName");

        conn = getConn();
        DatabaseMetaData dbmd = conn.getMetaData();
        dbProductName = dbmd.getDatabaseProductName();
    } catch (SQLException e) {
        Log.error(e, "TradeDirect:checkDBProductName() -- Error checking the Daytrader Database Product Name");
    } finally {
        releaseConn(conn);
    }
    return dbProductName;
}
 
Example 6
Source File: metaDatabase.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
private static boolean isPostgreSQLDatabase( DatabaseMetaData metaData )
	throws SQLException
{
	String dbName = metaData.getDatabaseProductName();
	if ( dbName.startsWith( "PostgreSQL" ) )
		return true;
		
	return false;
}
 
Example 7
Source File: DatabaseStatusChecker.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public Status check() {
    boolean ok;
    try {
        Connection connection = dataSource.getConnection();
        try {
            DatabaseMetaData metaData = connection.getMetaData();
            ResultSet resultSet = metaData.getTypeInfo();
            try {
                ok = resultSet.next();
            } finally {
                resultSet.close();
            }
            if (message == null) {
                message = metaData.getURL()
                    + " (" + metaData.getDatabaseProductName() 
                    + " " + metaData.getDatabaseProductVersion()
                    + ", " + getIsolation(metaData.getDefaultTransactionIsolation()) + ")";
            }
            if (version == 0) {
                version = metaData.getDatabaseMajorVersion();
            }
        } finally {
            connection.close();
        }
    } catch (Throwable e) {
        logger.error(e.getMessage(), e);
        ok = false;
    }
    return new Status(! ok ? Status.Level.ERROR : (version < 5 ? Status.Level.WARN : Status.Level.OK), message);
}
 
Example 8
Source File: DbConn.java    From XBatis-Code-Generator with Apache License 2.0 5 votes vote down vote up
private DatabaseMetaData printDatabaseMetaData() {
	DatabaseMetaData dbmd = null;
	ResultSet rs = null;
	try {
		dbmd = conn.getMetaData();
		/*
		 * 获取当前数据库的数据类型信息。返回18列数据,如下所示
		 */
		rs = dbmd.getTypeInfo();
		logger.info("===============================数据库支持的数据类型:");
		while (rs.next()) {
			logger.info("类型名称【"
					+ StringUtil.genLengthStr(rs.getString(1), 20)
					+ "】SqlType【"
					+ StringUtil.genLengthStr(rs.getString(2), 5)
					+ "】最大精度【"
					+ StringUtil.genLengthStr(rs.getString(3), 10) + "】");
		}
		/* 获取数据库信息 */
		String dbType = dbmd.getDatabaseProductName(); // 获取当前数据库是什么数据库。如mysql等。返回的是字符串。
		String dbVersion = dbmd.getDatabaseProductVersion(); // 获得数据库的版本。返回的字符串。
		String driverName = dbmd.getDriverName(); // 获得驱动程序的名称。返回字符串。
		String driverVersion = dbmd.getDriverVersion(); // 获得驱动程序的版本。返回字符串。
		logger.info("数据库类型【" + dbType + "】数据库版本【" + dbVersion + "】数据库驱动名称【"
				+ driverName + "】数据库驱动程序版本【" + driverVersion + "】");

	} catch (SQLException e) {
		logger.error("获取DataBaseMetaData元数据出错", e);
	}
	return dbmd;
}
 
Example 9
Source File: HyperSQLDialect.java    From jactiverecord with MIT License 5 votes vote down vote up
/**
 * 判断当前数据库的名称里是否包含hsql(忽略大小写)。
 * 
 * @param c 数据库连接
 * @return 如果数据库名称包含hsql,则返回true;否则返回false。
 */
@Override
public boolean accept(Connection c) {
  try {
    DatabaseMetaData d = c.getMetaData();
    String name = d.getDatabaseProductName(); // HSQL Database Engine
    return name.toLowerCase().contains("hsql");
  } catch (SQLException e) {
    throw new DBOpenException(e);
  }
}
 
Example 10
Source File: MySQLDialect.java    From jactiverecord with MIT License 5 votes vote down vote up
/**
 * 判断当前数据库的名称里是否包含mysql(忽略大小写)。
 * 
 * @param c 数据库连接
 * @return 如果数据库名称包含mysql,则返回true;否则返回false。
 */
@Override
public boolean accept(Connection c) {
  try {
    DatabaseMetaData d = c.getMetaData();
    String name = d.getDatabaseProductName(); // MySQL
    return name.toLowerCase().contains("mysql");
  } catch (SQLException e) {
    throw new DBOpenException(e);
  }
}
 
Example 11
Source File: SqlgPlugin.java    From sqlg with MIT License 5 votes vote down vote up
/**
 * Loads the plugin to use for the provided database meta data.
 * 
 * @param metaData the JDBC meta data from an established database connection
 * @return the plugin to use, never null
 * @throws IllegalStateException if no suitable Sqlg plugin could be found
 */
public static SqlgPlugin load(DatabaseMetaData metaData) throws SQLException {
    for (SqlgPlugin p : ServiceLoader.load(SqlgPlugin.class, SqlgPlugin.class.getClassLoader())) {
        if (p.canWorkWith(metaData)) {
            return p;
        }
    }
    throw new IllegalStateException("Could not find suitable Sqlg plugin for the database: " + metaData.getDatabaseProductName());
}
 
Example 12
Source File: DbUtil.java    From Alpine with Apache License 2.0 5 votes vote down vote up
public static void initPlatformName(Connection connection) {
    try {
        DatabaseMetaData dbmd = connection.getMetaData();
        platform = dbmd.getDatabaseProductName();
    } catch (SQLException e) {
        // throw it away
    }
}
 
Example 13
Source File: UnknownDatabaseInfoHelper.java    From dekaf with Apache License 2.0 5 votes vote down vote up
static UnknownDatabaseInfo obtainDatabaseInfo(Connection connection) throws SQLException {
  DatabaseMetaData md = connection.getMetaData();
  String databaseProductName = md.getDatabaseProductName();
  return databaseProductName != null
      ? obtainDatabaseInfo(databaseProductName)
      : makeDefaultUnknownInfo();
}
 
Example 14
Source File: StatementCreatorUtils.java    From spring-analysis-note with MIT License 4 votes vote down vote up
/**
 * Set the specified PreparedStatement parameter to null,
 * respecting database-specific peculiarities.
 */
private static void setNull(PreparedStatement ps, int paramIndex, int sqlType, @Nullable String typeName)
		throws SQLException {

	if (sqlType == SqlTypeValue.TYPE_UNKNOWN || (sqlType == Types.OTHER && typeName == null)) {
		boolean useSetObject = false;
		Integer sqlTypeToUse = null;
		if (!shouldIgnoreGetParameterType) {
			try {
				sqlTypeToUse = ps.getParameterMetaData().getParameterType(paramIndex);
			}
			catch (SQLException ex) {
				if (logger.isDebugEnabled()) {
					logger.debug("JDBC getParameterType call failed - using fallback method instead: " + ex);
				}
			}
		}
		if (sqlTypeToUse == null) {
			// Proceed with database-specific checks
			sqlTypeToUse = Types.NULL;
			DatabaseMetaData dbmd = ps.getConnection().getMetaData();
			String jdbcDriverName = dbmd.getDriverName();
			String databaseProductName = dbmd.getDatabaseProductName();
			if (databaseProductName.startsWith("Informix") ||
					(jdbcDriverName.startsWith("Microsoft") && jdbcDriverName.contains("SQL Server"))) {
					// "Microsoft SQL Server JDBC Driver 3.0" versus "Microsoft JDBC Driver 4.0 for SQL Server"
				useSetObject = true;
			}
			else if (databaseProductName.startsWith("DB2") ||
					jdbcDriverName.startsWith("jConnect") ||
					jdbcDriverName.startsWith("SQLServer")||
					jdbcDriverName.startsWith("Apache Derby")) {
				sqlTypeToUse = Types.VARCHAR;
			}
		}
		if (useSetObject) {
			ps.setObject(paramIndex, null);
		}
		else {
			ps.setNull(paramIndex, sqlTypeToUse);
		}
	}
	else if (typeName != null) {
		ps.setNull(paramIndex, sqlType, typeName);
	}
	else {
		ps.setNull(paramIndex, sqlType);
	}
}
 
Example 15
Source File: DatabaseConnectionEditor.java    From MogwaiERDesignerNG with GNU General Public License v3.0 4 votes vote down vote up
private void commandTest() {

		if (bindingInfo.validate().isEmpty()) {

			bindingInfo.view2model();

			DatabaseConnectionDatamodel theModel = bindingInfo
					.getDefaultModel();

			Dialect theDialect = theModel.getDialect();

			try {

				Connection theConnection = theDialect.createConnection(
						ApplicationPreferences.getInstance()
								.createDriverClassLoader(), theModel
								.getDriver(), theModel.getUrl(), theModel
								.getUser(), theModel.getPassword(), theModel
								.isPromptForPassword());
				if (theConnection == null) {
					return;
				}

				DatabaseMetaData theMeta = theConnection.getMetaData();

				String theDB = theMeta.getDatabaseProductName();
				String theVersion = theMeta.getDatabaseProductVersion();

				if (!theDialect.generatesManagedConnection()) {
					theConnection.close();
				}

				MessagesHelper.displayInfoMessage(this, getResourceHelper()
						.getText(ERDesignerBundle.CONNECTIONSEEMSTOBEOK)
						+ " DB : " + theDB + " " + theVersion);

			} catch (Exception e) {

				MessagesHelper.displayErrorMessage(this, e.getMessage());
			}
		}
	}
 
Example 16
Source File: BizDataObjectBehaviorImpl.java    From FoxBPM with Apache License 2.0 4 votes vote down vote up
public List<BizDataObject> getDataObjects(String dataSource) {
	LOG.debug("getDataObjects(String dataSource),dataSource=" + dataSource);
	try {
		JdbcTemplate jdbcTemplate = new JdbcTemplate(DBUtils.getDataSource());
		DatabaseMetaData dm = DBUtils.getDataSource().getConnection().getMetaData();
		String databaseType = dm.getDatabaseProductName();
		String databaseVersion = dm.getDatabaseProductVersion();
		LOG.info("the database type is " + databaseType + ",version is " + databaseVersion);
		// 定义sql返回结果集
		SqlRowSet rs = null;
		boolean isOracle = false;
		if (MySQL_TYPE.equalsIgnoreCase(databaseType)) {
			// 获取此 当前数据源连接 对象的当前目录名称。
			String catalog = jdbcTemplate.getDataSource().getConnection().getCatalog();
			LOG.info("the sql is " + TABLE_INFOR);
			rs = jdbcTemplate.queryForRowSet(TABLE_INFOR, new Object[]{catalog});
		} else if (ORACLE_TYPE.equalsIgnoreCase(databaseType)) {
			isOracle = true;
			StringBuffer sql = new StringBuffer("select distinct t_col.DATA_TYPE,t_col.TABLE_NAME,t_col.COLUMN_NAME,t_des.comments as TABLE_COMMENT,c_des.comments as COLUMN_COMMENT from user_tab_columns t_col,user_col_comments c_des,user_tab_comments t_des ").append("where t_col.table_name = c_des.table_name and t_col.table_name = t_des.table_name order by t_col.table_name");
			rs = jdbcTemplate.queryForRowSet(sql.toString());
		} else if("mssql".equalsIgnoreCase(databaseType)){
			
		}
		
		
		List<BizDataObject> bizDataObjects = new ArrayList<BizDataObject>();
		BizDataObject bizDataObject = null;
		DataVariableDefinition dataVariableDefine = null;
		String tableName = null;
		StringBuffer sbExpression = new StringBuffer();
		if(rs != null){
		// 获取表信息
		while (rs.next()) {
			// 处理首次和区分不同表
			if (!rs.getString(TABLE_NAME).equals(tableName)) {
				bizDataObject = new BizDataObject();
				bizDataObject.setId(rs.getString(TABLE_NAME));
				if (isOracle) {
					bizDataObject.setName(rs.getString(TABLE_COMMENT));
				}
				bizDataObject.setDataSource(dataSource);
				// 添加业务数据对象
				bizDataObjects.add(bizDataObject);
			}
			dataVariableDefine = new DataVariableDefinition();
			dataVariableDefine.setId(rs.getString(COLUMN_NAME));
			dataVariableDefine.setFieldName(rs.getString(COLUMN_NAME));
			dataVariableDefine.setDataType(rs.getString(DATA_TYPE));
			// 生成表达式
			sbExpression.append("import org.foxbpm.engine.impl.util.DataVarUtil;\n");
			sbExpression.append("DataVarUtil.getInstance().getDataValue(");
			sbExpression.append("\"" + dataSource + "\"").append(',').append("processInfo.getProcessInstance().getBizKey(),");
			sbExpression.append("\"" + dataVariableDefine.getId() + "\"");
			sbExpression.append(",processInfo);");
			dataVariableDefine.setExpression(sbExpression.toString());
			
			dataVariableDefine.setDocumentation(rs.getString(COLUMN_COMMENT));
			dataVariableDefine.setBizType(Constant.DB_BIZTYPE);
			// 添加数据变量定义
			bizDataObject.getDataVariableDefinitions().add(dataVariableDefine);
			tableName = rs.getString(TABLE_NAME);
			// 清空sbExpression缓存
			sbExpression.delete(0, sbExpression.length());
		}}
		LOG.debug("end getDataObjects(String dataSource)");
		return bizDataObjects;
	} catch (SQLException e) {
		throw ExceptionUtil.getException("获取数据对象失败",e);
	}
}
 
Example 17
Source File: MysqlIntermediateFacade.java    From dekaf with Apache License 2.0 4 votes vote down vote up
@Override
public ConnectionInfo obtainConnectionInfoNatively() {
  String[] env;
  Version serverVersion = null, driverVersion;

  final JdbcIntermediateSession session = openSession();
  try {
    // environment
    env = session.queryOneRow(CONNECTION_INFO_QUERY, 4, String.class);
    String verComment = env == null ? null : env[3];
    if (verComment != null) verComment = verComment.toLowerCase(Locale.ENGLISH);
    if (env == null) env = new String[] {null, null, null};

    // versions
    String rdbmsName, serverVersionStr, driverVersionStr;
    try {
      DatabaseMetaData md = session.getConnection().getMetaData();
      serverVersionStr = md.getDatabaseProductVersion();
      driverVersionStr = md.getDriverVersion();
      rdbmsName = md.getDatabaseProductName();
      if (rdbmsName == null) rdbmsName = session.getConnection().getClass().getName();
    }
    catch (SQLException sqle) {
      throw getExceptionRecognizer().recognizeException(sqle, "getting versions using JDBC metadata");
    }

    if (rdbmsName.equals("MySQL")) {
      int pos = serverVersionStr.indexOf(Mysql.MARIADB_FLAVOUR);
      if (pos != -1) {
        serverVersion = extractMariaVersionImpl(pos, serverVersionStr);
        if (serverVersion != Version.ZERO) rdbmsName = Mysql.MARIADB_FLAVOUR;
        else serverVersion = null;
      }
      else if (verComment != null) {
        if (verComment.startsWith("memsql")) {
          rdbmsName = Mysql.MEMSQL_FLAVOUR;
          String[] memVer = session.queryOneRow("select @@memsql_version", 1, String.class);
          if (memVer != null && memVer[0] != null) serverVersion = extractVersion(memVer[0], SIMPLE_VERSION_PATTERN, 1);
        }
        else if (verComment.startsWith("mariadb")) rdbmsName = Mysql.MARIADB_FLAVOUR;
      }
    }

    if (serverVersion == null) serverVersion = extractVersion(serverVersionStr, SIMPLE_VERSION_PATTERN, 1);
    driverVersion = extractVersion(driverVersionStr, SIMPLE_VERSION_PATTERN, 1);

    // ok
    return new ConnectionInfo(rdbmsName, env[0], env[1], env[2], serverVersion, driverVersion);
  }
  finally {
    session.close();
  }
}
 
Example 18
Source File: MySqlDatabase.java    From barleydb with GNU Lesser General Public License v3.0 4 votes vote down vote up
public MySqlDatabase(DatabaseMetaData metaData) throws SQLException {
    info = metaData.getDatabaseProductName() + " " + metaData.getDatabaseProductVersion();
}
 
Example 19
Source File: HsqlDatabase.java    From barleydb with GNU Lesser General Public License v3.0 4 votes vote down vote up
public HsqlDatabase(DatabaseMetaData metaData) throws SQLException {
    info = metaData.getDatabaseProductName() + " " + metaData.getDatabaseProductVersion();
}
 
Example 20
Source File: Globals.java    From nextreports-designer with Apache License 2.0 4 votes vote down vote up
public static String getDatabaseName(Connection conn) throws Exception {
    DatabaseMetaData dbmd = conn.getMetaData();
    return dbmd.getDatabaseProductName();
}