What is the best way to get database name use java metadata - java

In my application using different databases (postgres, mssql, oracle ...). What is the best way to get database name use metadata. I was trying to use this approach:
try (final Connection connection = jdbcTemplate.getDataSource().getConnection()) {
final DatabaseMetaData metaData = connection.getMetaData();
final String databaseName = StringUtils.substringAfterLast(connection.getMetaData().getURL(), "/");
It works in this case:
spring.datasource.url=jdbc:mysql://localhost:3306/2022_2
But in this case it doesn't work:
spring.datasource.url=jdbc:sqlserver://localhost:1433;DatabaseName=test_mssql;encrypt=true;trustServerCertificate=true;

You may consider using Connection#getCatalog() for your case.
Please see the following example below:
try (final Connection connection = jdbcTemplate.getDataSource().getConnection()) {
String databaseName = connection.getCatalog();
} catch (SQLException e) {
e.printStackTrace();
}

Related

I need details of trigger from any database using Java but this code (from previous answer) doesn't work

I'm looking for a way to get information about triggers (like name and other details) in MS_SQL, MySQL, PostgreSQL, and Oracle.
I found the following code in this answer but when I tried using it with a MySQL database it did not work.
package jdbc.core;
import java.sql.*;
public class ListProcedures {
public static void main(String[] args) {
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/db1", "root", "xxx");
DatabaseMetaData meta = con.getMetaData();
ResultSet res = meta.getTables(null, "root", "public", new String[] { "TRIGGER" });
System.out.println("List Of the trigger :-");
while (res.next()) {
// res.getString("TABLE_NAME");
System.out.println("!!" + res.getString(1));
System.out.println("::" + res.getString(2));
System.out.println("::" + res.getString(3));
}
res.close();enter code here
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Can anyone suggest some other way to retrieve the information I need?
There is nothing in JDBC that defines how to obtain information on triggers. This means you can only use driver-specific quirks like using a 'table'-type "TRIGGER" with Oracle, or maybe a driver-specific extension in another driver.
So in general the answer is: you can't.

how can i connect from java to mysql server?

The error is that I cant open the connection to mysql database, it must be an error in parameters but I am confused , I have no idea where is the problem.
First you need to create a MySQL schema. Secondly, use JDBC to connect to your recently created database (via localhost - make sure you get the user/password right).
After that you should use DAO-like classes. I'll leave here a Connect class:
public class Connect {
private static final String USERNAME = "root";
private static final String PASSWORD = "12345";
private static final String URL = "localhost";
private static final String SCHEMA = "new_schema";
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection connect() throws SQLException {
return DriverManager.getConnection("jdbc:mysql://"+URL+"/"+SCHEMA+"?user="+USERNAME+"&password="+PASSWORD);
}
}
After you have the Connect class, you should connect to the database using Connection c = Connect.connect(). Here's a class that implements it.
public static List<Album> list() throws SQLException {
Connection c = Connect.connect();
ResultSet rs = c.createStatement().executeQuery("SELECT * FROM Albums");
List<Album> list = new ArrayList<>();
while (rs.next()) {
String name = rs.getString("nome"); // first table column (can also use 1)
String artist = rs.getString("artista"); // second table column (can also use 2)
Album a = new Album(name, artist);
list.add(a);
}
return list;
}
It should also give you an insight as to how you should use SQL commands.
If you'd like a more in-depth help you should post the code you used, otherwise it's difficult to give you a more "to-the-point" explanation.
JDBC URLs can be confusing. Suggest you try using a SQL tool that understands the JDBC protocol (such as the database development perspective in Eclipse) to validate the URL and make sure you can connect to the database before you start coding. Cutting and pasting a URL known to work into your code can avoid many problems.

Can I connect to h2 embedded db without setting Class.forName("org.h2.Driver")?

Can I connect to h2 embedded db without setting Class.forName("org.h2.Driver") ?
I used only those parameters: url, login and pass
public static Connection getConnection() {
String url= ResourseHelper.getUrl();
String user= ResourseHelper.getUser();
String pass= ResourseHelper.getPass();
try {
return DriverManager.getConnection(url, user, pass);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
And than I create embedded database using this connection. And it works. Is it correct?
Yes, for Java 1.6 and newer, Class.forName("org.h2.Driver") is no longer needed. This is due to a change in JDBC 4.0. For details, see Getting Connected Becomes Easier.

Get data from MS Access DB using StelsMDB on Android

I'm trying to access a MS_Access db using StelsMDB library. The file is on the SD card of the phone. I loaded all libraries, created the connection:
public class DBConnection {
private static final String TAG = DBConnection.class.getSimpleName();
private Connection connection;
public DBConnection() {
try {
Class.forName(jstels.jdbc.mdb.MDBDriver2.class.getName());
connection = DriverManager.getConnection("jdbc:jstels:mdb:sdcard/2012xp.mdb");
} catch (SQLException e) {
Log.e(TAG, "", e);
} catch (ClassNotFoundException e1) {
Log.e(TAG, "", e1);
}
}
public Connection getConnection() {
return this.connection;
}
}
and it seems to work; but when i try to query something i get the following exception:
Failed parsing query
java.lang.IllegalStateException: unknown query object flag 3
Online i can't find any hint. I get this exception with a complex query, so i tryied to write an easier one like
"SELECT * FROM TABLE_NAME"
....but i get the same exception.
I belive you have a mistake in the connection string. You need to creat Connection object with it's atributes.
Try replacing your connection with this:
Connection conn = DriverManager.getConnection("jdbc:jstels:mdb:sdcard/2012xp.mdb");
After a long trying i found out that jStels is not compatible with android...

Java Wont connect to database no matter what driver

import java.sql.*;
public class Connect
{
public static void main (String[] args)
{
Connection conn = null;
try
{
String userName = "root";
String password = "password123!";
String url = "jdbc:oracle:thin:#localhost:3306:procomport";
//Class.forName ("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, userName, password);
//Connection connection = DriverManager.getConnection(url , userName, password);
System.out.println ("Database connection established");
}
catch (Exception e)
{
System.err.println ("Cannot connect to database server");
}
finally
{
if (conn != null)
{
try
{
conn.close ();
System.out.println ("Database connection terminated");
}
catch (Exception e) { /* ignore close errors */ }
}
}
}
}
This is my code I have multiple different databases but it wont connect to any of them what's the problem with this? I keep getting the error it cannot connect to the database. Although I can connect to it using other management tools is it a driver issue? How would I be able to tell if I had the drivers necessary?
The code you've provided to connect to the database won't connect to either MySQL nor Oracle as it stands because it's a mish-mash of attempts to connect to both.
For Oracle, the code should look something like:
String userName = "root";
String password = "password123!";
String url = "jdbc:oracle:thin:#localhost:1521:procomport";
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, userName, password);
(assuming you have a user called root on Oracle, and the Oracle SID is procomport). Note in particular the change of port number: MySQL typically uses 3306, Oracle uses 1521.
For MySQL the connection code should look like:
String userName = "root";
String password = "password123!";
String url = "jdbc:mysql://localhost:3306/procomport";
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, userName, password);
(assuming your MySQL database is called procomport). Note the different style of connection URL and the driver class name.
The Oracle driver is typically in a JAR file named ojdbc6.jar, and the MySQL in a JAR named something like mysql-connector-java-5.1.18-bin.jar.
Finally, when you write something like
catch (Exception e)
{
System.err.println ("Cannot connect to database server");
}
you really aren't helping yourself. The exception e will almost certainly contain the reason why your database connection code isn't working, but by deliberately ignoring it you're making it much harder for yourself to figure out what has gone wrong.
To be honest with you, I'd be tempted to declare the main method throws Exception (by adding this to the end of the public static void main... line), and then you can delete your unhelpful catch block. If an exception is thrown and not handled within main, the JVM will print the stack trace for you before it exits.
After your:
System.err.println();
Place a:
e.printStacktrace();
Then you will see real error message. Probably the driver classes are not in the classpath.
Hope this will help you
Uncomment the line Class.forName("oracle.jdbc.driver.OracleDriver");
Make sure you have the Oracle dirver "oracle.jdbc.driver.OracleDriver" in the classpath

Categories