How to determine the DBMS from Connection object - java

I have a usecase of supporting multiple RDBMS. User should define the data source as a prerequisite and at the code level i have to determine which RDBMS the user going to connect with and provide specific RDBMS attributes.
Eg:,
com.mysql.jdbc.Driver jdbc:mysql://hostname/ databaseName
oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:#hostname:port Number:databaseName
As shown above we can retrieve connection url or may be driver name and identify the RDBMS. But i want to clarify what is the best way to identify which RDBMS user is using. Any help would be greatly appreciated.

This is really simple. See DatabaseMetaData
DatabaseMetaData databaseMetaData = connection.getMetaData();
String databaseName = databaseMetaData.getDatabaseProductName();
String userName = databaseMetaData.getUserName();
UPDATE To answer #dnWick comment.
Yes, This DatabaseMetaData support for the wide range of RDBMS. Through the DatabaseMetaData interface we can obtain metadata about the database that we have connected. For instance, we can see what tables are defined in the database, and what columns each table has, Even we can check supported features for the database we have connected.
Example We can see if a database has support for multiple transactions, supports for UNION or not, etc.,

Related

Are all JDBC Plugins Compatible?

This is just a theoretical question, but I am building a program that gets data from Facebook using the CDATA JDBC Plugin, I wanted to know if all JDBC Plugins have the same syntax. For example, if I just change the JAR file for the driver to a Twitter one, and change the names of the tables and columns I am accessing, would it still work?
By a plugin I mean a driver, also, to put it more clearly, if I was developing a MySQL app and switched from the stock Connector/J Driver to the CData driver, would I need to change the code?
Until the underlying schema where you store remains same, the use of JDBC driver will yield the same result.
Note: Twitter/FB... both has to support the JDBC Model...
However, if you have changes in Drivers, you can consider using ApacheMetamodel Link for reference
JDBC is a standard that has been established and vetted over the years. As long as the drivers you're working with are written to that standard (which as a CData employee, I can say that ours are) you can expect your code referencing a JDBC driver to be essentially identical, regardless of the manufacturer of the driver or the data source you're connecting to.
//optional, register the driver with the DriverManager
Class.forName(myDriverName).newInstance();
//obtain a Connection instance from the DriverManager
Connection conn = null;
try {
conn = DriverManager.getConnection(myJDBCurl);
//execute a select query
Statement stmt = conn.createStatement();
Result rs = stmt.executeQuery("SELECT foo FROM bar");
} catch (SQLException ex) {
//handle any errors
}
As you can see, the code to utilize the JDBC driver can be generalized with variables to use any driver or to use different connections under a single driver (if, for instance, you wanted to connect to different Facebook accounts).
JDBC is an interesting standard. It was intentionally designed to load the driver at run-time, so no vendor classes are used during compilation.
It also has some JDBC own mechanisms for schema data (DatabaseMetaData), and for such things as doing an INSERT with an autoincrement key, and retrieving that key (getGeneratedKeys).
However the SQL is far from standardized by vendor, despite standardisation efforts. For example just getting the first 10 rows.
Unfortunately the visionaries of JDBC seem no longer to exist.
But it a sound basis for professional usage.

Java DB Database, check for all table names

I've got an embedded Derby Database in my java application, and have multiple table's (that are created and deleted, so nothing is set in stone). I wanted to be able to return a list of names of all the tables currently in the database as I have to display the list in the application as well as get all the information from them.
Easiest way to do so? I don't need code just a method or methods. I'm a terrible google-fu user.
Currently my code works by grabbing a ResultSet from a specific table name entered, but it's only for testing purposes and I need to be able to display the full list of tables I have.
EDIT: My current workaround is actually different than posted. I simply have another table that holds all the table names created and updates when one is created/deleted. Obviously not the best approach but it works for me right now.
DatabaseMetaData metaData = connection.getMetaData();
ResultSet resultSet = metaData.getTables(null, "schenaName", "%" ,new String[] {"TABLE"} );
while (resultSet.next()) {
System.out.println(resultSet.getString(3));
}
Adding new answer:
Connection connection = getDBConnection();
DatabaseMetaData dbMetaData = connection.getMetaData();
//getting catalogs for mysql DB, if it is not working for your DB, try dbMetaData.getSchemas();
ResultSet catalogs = dbMetaData.getCatalogs();
while(catalogs.next()){
String catalogName = catalogs.getString(1);
//excluding table names from "mysql" schema from mysql DB.
if(!"mysql".equalsIgnoreCase(catalogName)){
ResultSet tables = dbMetaData.getTables(catalogName, null, null, null);
while(tables.next()){
System.out.println(catalogName + "::"+tables.getString(3));
}
}
}
Using metadata is the (somewhat) more portable solution. Note that you don't need the catalog stuff with Derby, as there are no catalogs. You can issue dmd.getTables(...) directly with null for the catalog. If all the tables you track are in a single schema, (and there aren't any other tables in that schema), getTables(null, "schemaName", null, null) should do the trick.
If need more fancy querying and you're not concerned about portability, you can check out
the dataBaseMetaData tool which gives you access to metadata as tables so that you can perform joins and other sophisticated queries on them.
Try this:
select tableName from sys.systables
You should get all the tables your system.

Connecting to Oracle with JDBC causes queries to return zero rows.

So I have been playing around with querying databases using the standard
Statement s = connection.createStatement();
ResultSet rs = s.executQuery(queryString);
ResultSetMetadata rsmd = rs.getMetaData();
while(rs.next)){
String code = "";
String value = "";
for(int i = 1; i <= rsmd.getColumnCount(); i++){
Object obj = rs.getObject(i);
if(i == 1){
code = obj.toString():
}
else{
label = obj.toString();
}
}
//Store code and labels in map
}
...go on to close statement and move on.
I am trying to select two columns from a table in each instance.
For the most part this works well. When working with MySql & Microsoft Sql databases I get a result set full of data in the table. However when I try to do this with an Oracle database I get an empty result set.
I have tested my query string in the SQL Developer application and it works fine, returns my data. But the result set doesnt contain anything. The resultSet metadata says that it has two columns though. Is there anything I need to do when interacting with an Oracle Database that is different from the other two? Thanks.
If your query works when you run it against the Oracle database, and you know the code works since you've run it against MySQL, then some other things to try are:
1.) Make sure your JDBC connection URL is correct. Are you sure you are connecting to the database that you intend to? (i.e. - the one that would return the rows you expect?)
2.) Take into account credentials. Make sure you are using the same credentials through JDBC that you are when connecting to Oracle directly.
3.) Make sure both connections are being made from the same machine and with the same environment. Oracle drivers rely on environment variables to find a file (I believe it is called tnsnames.ora, or something like that) that contains the alias & connection info. Getting different versions of that file could point you to different Oracle instances.
4.) Try manually specifying your schema name in the query. So instead of select * from my_table use select * from my_schema.my_table. Sometimes Oracle clients will configure their sessions to have default schemas set up in their preferences.
5.) If your are attempting to select data that you've inserted with your Oracle client, make sure you've committed the transaction in your Oracle client so that the data is visible to other sessions.
One last debugging tool to use is to try connecting via the Squirrel DB client. Squirrel is a 100% pure java SQL client that connects to any DB using JDBC. It would be a good test to make sure your JDBC Driver, Connection URL, etc. are all valid.
The database table has records but the JDBC client can't retrieve the records. Means the JDBC client doesn't have the select privileges. Please run the below query on command line:
grant all on emp to hr;

JDBC:is it possible to execute multi-database Querys in java?

I want to execute an sql-query over 2 databases using java
but have some problems finding out how to do it without writing everything by myself
maybe someone has an idea how to do it.
example:
database1
table1(names): id,Name,zip,something
database2
table2(towns): id,townname,zip
SELECT *
FROM database1.names, database2.towns
WHERE database1.names.zip = database2.towns.zip
the example works in mysql when i use phpMyAdmin and the User has rights on both databases
edit:
The question is: How do i get Java to execute such a query since i can only connect to one database(?)
or: How can I connect to 2 Databases executing an Sql Query that uses tables from both databases using java.
the way i execute sql commands in java looks like:
Connection c = DriverManager.getConnection("jdbc:mysql://localhost/database?user=root&password=");
PreparedStatement pstmt = c.prepareStatement("Select * from something");
pstmt.executeQuery();
but i cant use that to get a Sql Query that uses tables from 2 databases?
Assuming that these databases are not visible from the same datasource, you have to use a mediation software to query on them, such as http://www.unityjdbc.com/doc/multiple/multiplequery.php.
It's not a trivial problem, since your "SQL" will have to deal with each datasource availability and transaction.
Some DB vendors provide some sort of dblinks (e.g. http://docs.oracle.com/cd/B19306_01/server.102/b14200/statements_5005.htm) that help you a little to deal with heterogeneous DBs.
So it would be nice if you narrow your question to what DBMSs you are interested.

What are alternatives to JDBC driver for access PostgreSQL database

I'm using official JDBC driver for PostgreSQL, but I'm stuck with the following issues:
No support for PostgreSQL-ish data structures such as UUIDs.
Common JDBC weirdness, such as:
No function to escape values for consuming by PostgreSQL.
Limited support for executing heterogeneous statements in batch.
No rewriting of multiple insert statements into single insert statement when inserting many rows in one table.
So, the question — is there any PostgreSQL database driver which can leverage full power of PostgreSQL without much boilerplate? I'm also use Scala language for development, so if driver is designed specifically for Scala it would be so much awesome awesome.
Some of this seems to be (unless I'm not understanding) user error in using JDBC. JDBC is a pretty ugly API, so never ask if you can do it elegantly, just ask if you can do it at all.
Escaping and inserting multiple rows should be handled, as #ColinD and #a_horse pointed out, with Prepared statements and batch operations. Under the hood, I would expect a good JDBC implementation to do the things you want (I am not familiar with PostgreSQL's implementation).
Regarding UUIDs, here is a solution:
All that PostgreSQL can do is convert string literals to uuid.
You can make use of this by using the data type
org.postgresql.util.PGobject, which is a general class used to
represent data types unknown to JDBC.
You can define a helper class:
public class UUID extends org.postgresql.util.PGobject {
public static final long serialVersionUID = 668353936136517917L;
public UUID(String s) throws java.sql.SQLException {
super();
this.setType("uuid");
this.setValue(s);
}
}
Then the following piece of code will succeed:
java.sql.PreparedStatement stmt =
conn.prepareStatement("UPDATE t SET uid = ? WHERE id = 1");
stmt.setObject(1, new UUID("a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11"));
stmt.executeUpdate();
The driver supports batched statements to speed up bulk inserts.
And using batched statements is a lot more portable than using proprietary INSERT syntax (and as far as I can tell, there is no big different between a multi-row insert and batched inserts)
Check out PreparedStatement.addBatch()
The reason why UUID is not supported is probably that UUID is not part of the Postgres core, just a contrib module.
Edit
Regarding the execute heterogeneous statements
The Postgres driver does support different types of statements in the a batch.
The following works fine:
Connection con = DriverManager.getConnection("jdbc:postgresql://localhost/postgres", "foo", "bar");
con.setAutoCommit(false);
Statement stmt = con.createStatement();
stmt.addBatch("create table foo (id integer, data varchar(100))");
stmt.addBatch("insert into foo values (1, 'one')");
stmt.addBatch("insert into foo values (2, 'two')");
stmt.addBatch("update foo set data = 'one_other' where id = 1");
stmt.executeBatch();
con.commit();
Although you do lose the automatic escaping that PreparedStatement gives you.
I realise this doesn't answer your entire question, but hopefully it will be useful all the same.
I'm using Java 6 and Postgres 8.4. The driver I'm using is in my Maven POM file as:
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>8.4-702.jdbc4</version>
</dependency>
I'm using PreparedStatement.getObject() and PreparedStatement.setObject() with Java's java.util.UUID class to retrieve and store UUIDs.
For example:
pstm.setObject(1, guid); //where pstm is a PreparedStatement and guid is a UUID
and:
//where rs is a ResultSet
UUID myGuid = (UUID) rs.getObject("my_uuid_column_name");
Works fine.
With newer drivers, the following is alsow supported
UUID myGuid = rs.getObject("my_uuid_column_name", UUID.class);
No support for PostgreSQL-ish data structures such as UUIDs.
On the contrary, the current JDBC driver (9.2-1002 JDBC 4) for Postgres 9.x does indeed support UUID via the setObject and getObject commands. You cannot get any more direct or simpler than that (in any database, Postgres or any other) because JDBC does not recognize UUID as a data type.
As far as I can tell, there is no need to create a helper class as suggest in another answer by Yishai.
No need to do any casting or go through strings.
See my blog post for more discussion and code example.
Code example excerpt:
java.util.UUID uuid = java.util.UUID.randomUUID();
…
preparedStatement.setObject( nthPlaceholder++, uuid ); // Pass UUID to database.
Take a look at O/R Broker, which is a Scala JDBC-based library for relational database access.

Categories

Resources