From within a java code - where I already have a connection to a database - I need to find the default schema of the connection.
I have the following code that gives me a list of all schemas of that connection.
rs = transactionManager.getDataSource().getConnection().getMetaData().getSchemas();
while (rs.next()) {
log.debug("The schema is {} and the catalogue is {} ", rs.getString(1), rs.getString(2));
}
However, I don't want the list of all the schemas. I need the default schema of this connection.
Please help.
Note1: I am using H2 and DB2 on Windows7 (dev box) and Linux Redhat (production box)
Note2: I finally concluded that it was not possible to use the Connections object in Java to find the default schema of both H2 and DB2 using the same code. I fixed the problem with a configuration file. However, if someone can share a solution, I could go back and refactor the code.
Please use connection.getMetaData().getURL() method which returns String like
jdbc:mysql://localhost:3306/?autoReconnect=true&useUnicode=true&characterEncoding=utf8
We can parse it easily and get the schema name. It works for all JDBC drivers.
Related
I am looking for a way to save an SQL database and then reference it by means other than localhost which would not work because it is being used on other computers.
I realize that my terminology may not be correct in asking for a means to "package" an SQL database however I am not very sure how to put my desire such a concise title.
I have a database that I created through mySQL here: http://gyazo.com/fcac155a60c0d2587442c3e4807ef98a
I can access this database with no problems through the following code...
try
{
//Get connection
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/term_database","root", "_cA\"#8X(XHm+++E");
//**********
//Connection myConn = DriverManager.getConnection("jdbc:mysql:translationDatabase","root", "_cA\"#8X(XHm+++E");
//**********
//create statement
Statement myStmt = myConn.createStatement();
//execute sql query
ResultSet myRs = myStmt.executeQuery("select * from terms WHERE idNumber=" +termNumber);
//process result set
while(myRs.next()){
term= (myRs.getString(language));
}
}
catch (Exception exc)
{
exc.printStackTrace();
}
However, I assume that my users will be on different computers and so a "//localhost" reference will not work. They do not have access to the internet either. So I aim to include the database in my program's files to be downloaded with the software or to include it in the jar. I was not able to find any means to do that online. The code I surrounded with *'s was an attempt to reference translationDatabase.sql which I saved through the program mySQL into my software's directory but it did not work as shown here: http://gyazo.com/e9d4339435dedecab4e7ad960e9b13b6
To recap: I am looking for a way to save an SQL database and then reference it by means other than localhost which would not work because it is being used on other computers.
The idiomatic terminology is "embedded" or "serverless" database.
There are several pure-java solutions. There is also the popular SQLite, which you can manipulate via its command line client, or via a third-party JDBC driver (example 1, example 2)
Any of the above solutions will require that you convert your existing MySQL database to the target system..
Alternatively, you may consider bundling your application with MySQL server (possibly with an automated installation process, so that installation is invisible to the end-user).
Running Netcool 7.3.1. Looking for simple api to access Object Server Tables. I've already done the run an SQL command from nco_sql, and scraped the output into a C# data table, but wondering if there was some type of api that I could use for either C# or Java to access table data?
If you can use a more up-to-date version of Omnibus, you can use the built-in HTTP / REST API.
http://www-01.ibm.com/support/knowledgecenter/SSSHTQ_8.1.0/com.ibm.netcool_OMNIbus.doc_8.1.0/omnibus/wip/api/concept/omn_api_http_overview.html?lang=en
You may need to use sybase database adapter so far I have used below three ways to query netcool object server:
Free TDS - This is free sybase client.
Jconn3 - this is paid sybase client, but if you are using WebGUI/Impact, this driver comes with TIP.
nco_sql - here you may need to create a file with query and then pass it to nco_sql. This require extra effort to parse column wise information as output will be on console.
I prefer jconn3, simple and similar to jdbc driver, you only need this jar in classpath.
You can write your own java program to connect to Objectserver by simply initiating
//Load Sybase Driver
Class.forName("com.sybase.jdbc3.jdbc.SybDriver");
String url = "jdbc:sybase:Tds:" + host + ":" + port;
con = DriverManager.getConnection(url, user, pass);
Execute Statements
Statement stat = conn.createStatement();
ResultSet result = stat.executeQuery("Select count(*) from alerts.status");;`
I am new to JOOQ and love learning and using it.
I am at the point where I want to do some testing, but instead of testing
on the 'real' database I want to use a 'copy' of that database.
When using jdbc all it really took was changing the database name in the
create statement and using that name when connecting to the database.
I quickly discovered that anything I tried to write to my test database
was ending up in the production database
In the JOOQ documentation it looked like I could solve the problem with some mapping.
I added a Settings class and got the DSLContext using the settings, as shown below
My base database name is 'kpi'.
Connection conn = JooqUtil.getConnection("user", "pw", kpitest, hostip, sb);
Settings settings = new Settings()
.withRenderMapping(new RenderMapping()
.withSchemata(
new MappedSchema().withInput(kpi)
.withOutput(kpitest)));
// Add the settings to the DSLContext
if (sb.length() == 0) {
dsl = DSL.using(conn, SQLDialect.MYSQL, settings);
}
The above resulted in seeing the testName database being used,
BUT access to the tables and fields was using the productionName.
Going back to the documentation it looks like there is a way to map the tables
also but it looks like a lot of work.
Further reading, I found some settings in the configuration file using schemata
My current JOOQ configuration xml file contains
<inputSchema>kpi</inputSchema>
It looks like I should change it to something like
<inputSchema></inputSchema> << maybe drop altogether
<schemata>
<schema>
<inputSchema>kpi</inputSchema>
<outputSchema>kpi</outputSchema>
</schema>
<schema>
<inputSchema>kpi</inputSchema>
<outputSchema>kpitest</outputSchema>
</schema>
</schemata>
In reading the manual I was not sure if DEV and PRODUCTION names had literal significance or not.
What would help is a (real world) example where there was a production and test database,
or one develpment database per developer, and how the tables and fields were accessed
if there was a change in syntax. A change in syntax would be difficult for doing unit type testing though.
Thanks for any quidance and links to examples
Here's the code that gives me headaches:
public List<String> listColumnsForTable(String tableName) throws SQLException {
List<String> columns = new ArrayList<String>();
DatabaseMetaData metadata = _connection.getMetaData();
ResultSet resultSet = metadata.getColumns(null, null, tableName, null);
while (resultSet.next())
columns.add(resultSet.getString("COLUMN_NAME"));
return columns;
}
This code works fine with SQL Server (I haven't checked with MySQL, Oracle or others), but I need to run some integration tests on an in memory database. All the databases I tried (h2, hsqldb and derby) fail.
Here is the link on github.
If you want the full project (with tests for h2, hsqldb, derby and sql server) do the following:
git clone git://github.com/sensui/InMemoryColumns.git
cd InMemoryColumns
gradlew
All the dependencies will be automatically downloaded. If you want to check the library versions look in the build.gradle script.
Now import the project in your favorite IDE (eclipse or idea).
The tests are available in the DatabaseMetadataCheckerTests class (canListColumnsForTable and canCheckIfColumnsExistInTable).
Normally you shouldn't modify those. I have created 4 test classes that provide connection details for each in memory database and you need to run those (the DatabaseMetadataCheckerTests is abstract so you don't run that).
NOTE:
When/if you find a solution than the tests for that specific database will pass.
You can easily try other databases like Oracle or MySQL just by extending the DatabaseMetadataCheckerTests class and providing the connection details (check the other tests).
Issue solved
The table names and column names should be in UPPERCASE. Check this commit for details.
H2, HSQLDB (as well as Oracle and DB2) comply with the SQL standard and thus unquoted object names are folded to uppercase (SQL Server does not do that, it keeps whatever case you used plus it might be configured to be not case sensitive for string comparisons).
create table foo (id integer) will be stored as FOO with the column name ID in the system catalog.
So you will need to pass the table name in uppercase to the JDBC API calls.
A note on porting this to other DBMS:
Postgres does not comply with the standard here and folds everything to lowercase
For MySQL there is no definite answer on how it does this. It depends on various configuration settings (and the storage engine, and the filesystem) so you can never be sure how an unquoted table name will actually be stored in the system.
I'm trying to do with java and mysql the same I am used to with .net and SQL server:
By using Microsoft.SqlServer.Management.Smo I can access database structure information from my instance ( server name, table structure, columns, datatype, description, default value)
I tried to find to do the same with Java + MYSQL but it seems it is not so popular
any directions?
thanks
Ed
The simplest way to accomplish it is by retrying the connection metadata, first you open a connection:
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db", "user","****");
DatabaseMetaData metaData = conn.getMetaData();
then start navigating through the metadata, you can check the available operations in DatabaseMedata
DatabaseMetaData will be useful for your requirement.
please also check nearly similar stackoverflow question
use the DatabaseMetadata for get database related information.
Database Metadata