Get the connected mysql database name (JDBC) - java

How can get the name of the database name from connection object
try {
this.ds = (DataSource) new InitialContext().lookup("java:comp/env/jdbc/amger");
} catch (NamingException ne) {
}
Connection conObj = ds.getConnection();
How do I get that Database name from con

Probably the most straightforward way to get the database name from the JDBC Connection object itself is via the getCatalog() method:
Connection#getCatalog()
However, as Konstantin pointed out in his comment below, that value will not change if the current MySQL database is changed by issuing a USE dbname statement.
getCatalog() might still be useful in an application that
does not change databases, or
does things "The JDBC Way" by using setCatalog() to change the current database,
but for MySQL, using SELECT DATABASE() appears to be safer overall.
Note also that this potential discrepancy between getCatalog() and the actual current database depends on the behaviour of the particular JDBC driver. Out of curiosity I tried something similar with the Microsoft JDBC Driver 4.0 for SQL Server and .getCatalog() was indeed aware of the change to the current database immediately after running a USE dbname statement. That is, the code
String connectionUrl = "jdbc:sqlserver://localhost:52865;"
+ "databaseName=myDb;" + "integratedSecurity=true";
try (Connection con = DriverManager.getConnection(connectionUrl)) {
System.out.println(String.format(
"getCatalog() returns: %s",
con.getCatalog()));
try (Statement s = con.createStatement()) {
System.out.println(" Executing: USE master");
s.execute("USE master");
}
System.out.println(String.format(
"getCatalog() returns: %s",
con.getCatalog()));
} catch (Exception e) {
e.printStackTrace(System.out);
}
produced the following results:
getCatalog() returns: myDb
Executing: USE master
getCatalog() returns: master

If you know that DB is Mysql you could just perform SELECT DATABASE() on your connection and read the resulset with current database name in it.
Here is description of DATABASE function.

Let's assume you used url as "jdbc:mysql://localhost/test"
Then do the following:
DatabaseMetaData dmd = connection.getMetaData();
String url = dmd.getURL();
System.out.println(url.substring(url.lastIndexOf("/") + 1));

Run
System.out.println(connection.getMetaData().getURL());
Paste the output in notepad
search the value for 'databaseName=yourDBName'

Related

Willena sqlite jdbc cannot open SqlCipher db

I am trying to figure out how to encrypt a sqlite database in non-android java.
It does not seem to be super straight forward, but I Willena jdbc crypt which does seem to be able to create an encrypted database, but I simply cannot figure out how to access a SQLCipher 4 encrypted database with it.
Here is my code.
String path = "jdbc:sqlite:C:\\Users\\User1\\Desktop\\testServer232.db";
Connection connection = null;
try
{
// create a database connection
connection = DriverManager.getConnection(path+"?cipher=sqlcipher&key=a");
Statement statement = connection.createStatement();
statement.setQueryTimeout(30); // set timeout to 30 sec.
statement.executeUpdate("drop table if exists person");
statement.executeUpdate("create table person (id integer, name string)");
statement.executeUpdate("insert into person values(3, 'leo1')");
statement.executeUpdate("insert into person values(4, 'yui1')");
ResultSet rs = statement.executeQuery("select * from person");
while(rs.next())
{
// read the result set
System.out.println("name = " + rs.getString("name"));
System.out.println("id = " + rs.getInt("id"));
}
}
catch(SQLException e)
{
// if the error message is "out of memory",
// it probably means no database file is found
System.err.println(e.getMessage());
}
finally
{
try
{
if(connection != null)
connection.close();
}
catch(SQLException e)
{
// connection close failed.
System.err.println(e.getMessage());
}
}
This code does work, but I don't think that it produces a SqlCipher 4 encrypted database. When I try to open it with DB browser for Sqlite, it does not allow me access when I put the password = a.
Where am I going wrong?
Ok, so I ended up finding the creator of the repository. And he solved it easily and answered really fast.
Here is the solution:
Here are a few things that could be tested:
Use version 3.31.1
Try to do the database connection using "jdbc:sqlite:file:C:\Users\User1\Desktop\test.db?cipher=sqlcipher&key=password123"as URI (notice the added "file:").
Try to add the legacy parameter for SQLCipher as available here (https://github.com/Willena/sqlite-jdbc-crypt#aes-256-bit-cbc---sha1sha256sha512-hmac-sqlcipher). The URI will become something like this: "cipher=sqlcipher&key=password123&legacy=4"
This is now working for me. I recommend that others use it if they are interested in an easy way to do sqlcipher version 4 similarly to how it is done in an android project.

Syntax error in prepared statement that runs in SQL

I'm getting a syntax error in my prepared statement even though my query runs in SQL Management Studio. I am using GlassFish 4.1.1. What am I doing wrong?
I've tried switching the syntax around a bit but I always get an error.
Here is my connection pool code:
try {
InitialContext ic = new InitialContext();
dataSource = (DataSource) ic.lookup("java:comp/env/" + database);
} catch (Exception ex) {
ex.printStackTrace();
}
Here is my query code:
ConnectionPool pool = new ConnectionPool("BoxPointHAMBURGO");
Connection connection = pool.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
try {
String query = "SELECT Tabla FROM BoxPointHAMBURGO.dbo.NombresTablas";
ps = connection.prepareStatement(query);
rs = ps.executeQuery();
} catch (Exception ex) {
System.err.println("Error: " + ex.getMessage());
}
The error that I get is:
Syntax error: Encountered "." at line 1 column 39.
As per this answer the double dot .. operator results in default schema for the current database user being used for the query. However you shouldn't expect that SQL Management Studio query syntax will work when using JDBC. These are two completely different driver interfaces with different limitations, JDBC most likely being more restrictive.
You probably should select the BoxPointHAMBURGO database when you establish the JDBC connection. You would have to modify the JDBC URL as per Building the Connection URL the syntax is:
jdbc:sqlserver://localhost;databaseName=BoxPointHAMBURGO
and then remove the database name from the SQL query:
SELECT Tabla FROM dbo.NombresTablas
Do note that tables under dbo schema can only be accessed by the user that is the database owner.

Unable to figure out JDBC ClassNotFoundException (JTDS driver)

So a little background on my problem: I am trying to copy over a table on an Microsoft SQL system from an Oracle database. Besides giving password and user access to the table I cannot edit or do anything to the MSSQL database.
I successfully used the Oracle SQL Developer to connect and view the tables I want (using a third party JDBC driver), but I want to set up an automated copy-over into my Oracle database so I am attempting to use the same driver in some stored java code.
I have a java function that all it should do is go and count the number of entries in the table. So far my code looks like:
public static String getCount() {
Statement stmt = null;
Connection conn = null;
int rowCount = 0;
String message = "";
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
}
catch(ClassNotFoundException e) {
System.err.println("Error loading driver: " + e);
message = message + e + " -ER1 \n";
}
try {
conn = DriverManager.getConnection("jdbc:jtds:sqlserver://site.school.edu:2000/ACCESS", "user", "password");
stmt = conn.createStatement();
String strSelect = "select 1 as field;";
ResultSet rset = stmt.executeQuery(strSelect);
while (rset.next()) {
++rowCount;
}
}
catch(SQLException ex) {
ex.printStackTrace();
message = message + ex.getSQLState() + " -ER2";
}
finally {
try {
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch(SQLException ex) {
ex.printStackTrace();
message = message + ex.getSQLState() + "-ER3";
}
}
return message;
}
Which is being calling from a stored function :
CREATE OR REPLACE function Schema.java_testMessage return varchar2
as language java
name 'ConnectAndQuery.getCount() return java.lang.String';
Which I am calling from a script in TOAD:
set serveroutput on;
declare
words varchar2(400);
begin
words := KSL_ADMIN.java_testMessage;
dbms_output.put_line(words);
end;
However the result is that I'm getting:
java.lang.ClassNotFoundException: net/sourceforge/jtds/jdbc/Driver -ER1
08001 -ER2
PL/SQL procedure successfully completed.
I have the jar file within the class path, I can't think of any reason it shouldn't have the nessecary permissions to see the jar, and as far as I can tell I have everything spelled correctly.
Please help me figure out what I am doing wrong. Or if there is perhaps an easier way to go about connecting an Oracle DB to an MSSQL DB without really installing anything. Any knowledge on this is welcome as I am pretty new to a lot of this.
Oracle has its own internal java virtual machine and it does not use the system classpath. If you need external libraries you must “load” them into the internal JVM. You can do this using Oracle's loadjava tool.
See the Oracle's loadjava documentation (http://docs.oracle.com/cd/B28359_01/java.111/b31225/cheleven.htm#JJDEV10060)

My puzzle about JDBC4.0 new feature: No suitable driver found

Guys,
I know there are some new features in JDBC4.0 and one of them is that you don't need to load database drivers explicitly as the JDBC API will automatically load the driver when you call getConnection(). So I just wanna test it.
BTW, I use Eclipse as my Dev Tool.
Here are my code snippets:
public class Test002JDBCRowSet {
public static void main(String[] args) throws Exception{
String connURL = "jdbc:oracle:thin:#192.168.1.150:1521:";
String database = "bmdw";
String userName = "bmdw";
String passWd = "bmdw";
String driver = "oracle.jdbc.driver.OracleDriver";
String SQLStr = "select t.Empno, t.Ename, t.job, t.sal from employer t where t.sal > 1500";
/*
try{
Class.forName(driver);
}catch(ClassNotFoundException cnfe){
cnfe.printStackTrace();
}
*/
//Latest Method4 : Search for some data with RowSet, offline!
RowSetFactory rsf = RowSetProvider.newFactory();
try(
Connection conn = DriverManager.getConnection(connURL + database,userName,passWd);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(SQLStr);
CachedRowSet cachedRS = rsf.createCachedRowSet();){
cachedRS.populate(rs);
conn.close();
System.out.println("======Employee List -- Salary more than 1500======");
System.out.printf("%-15s%-15s%-15s%-15s%n","Employee No.","Employee Name","Employee Job","Employee Salary");
try{
while(rs.next()){
System.out.printf("%-15d%-15s%-15s%.2f%n",cachedRS.getInt(1),cachedRS.getString("ENAME"),cachedRS.getString("JOB"),cachedRS.getFloat(4));
}
}catch(SQLException sqle){
sqle.printStackTrace();
}
while(cachedRS.next()){
System.out.printf("%-15d%-15s%-15s%.2f%n",cachedRS.getInt(1),cachedRS.getString("ENAME"),cachedRS.getString("JOB"),cachedRS.getFloat(4));
}
}catch(SQLException sqle){
sqle.printStackTrace();
}
}
}
I got the runtime exception :
java.sql.SQLException: No suitable driver found for
jdbc:oracle:thin:#192.168.1.150:1521:bmdw
However, if I remove the comments about loading oracle driver explicitly, it works well.
And I'm sure I have already add the ojdbc14.jar into classpath.
So I don't know what happened. I'm trying to figure out how does the method 'getConnection()' works.
I checked System.getProperties() but there is no property named 'jdbc.driver'. Even if I added it and set the value to 'oracle.jdbc.driver.OracleDriver'. It still doesn't work.
I checked ClassLoader.getSystemResources("META-INF/services/" + Driver.class.getName()) and I found there is only one default file :
jar:file:/D:/Java/jdk1.7.0_03/jre/lib/resources.jar!/META-INF/services/java.sql.Driver
I has so far achieved little.
There might be some oversight in the configuration of Eclipse.
Hope anyone can help me.
Thanks.
I agree with #kordirko and his comment. OP also seems to have confirmed that his problem is resolved because of his comment. Hopefully he gets notification of this and makes it an answer. :)
Check this link: http://docs.oracle.com/cd/E11882_01/java.112/e16548/jdbcvers.htm#JJDBC28109 --> You need to have the ojdbc6.jar in your classpath environment variable in order to have JDBC 4.0 standard support. – kordirko

Why am I receiving this SQLException error stating that no suitable driver can be found?

I'm on a mac, running a MAMP instance of MySQL. I'm trying to use a jdbc driver to connect my java code to a database called 'test', working with a table called 'customer.' I keep getting an error:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:8889/test
I'm not sure if the problem is with my code, or if it's a configuration problem with the MAMP instance of MySQL, or if it's something else entirely.
I have an initialize driver method:
public void initializeDriver(){
try{
Class.forName("com.mysql.jdbc.Driver");
}
catch(ClassNotFoundException e) {
System.err.println(e.toString());
}
}
And I have a connection created in the following way:
public void insertCustomer(String connectionUrl, String connectionUser, String connectionPassword, Customer customer) {
try{
Connection conn = DriverManager.getConnection(connectionUrl, connectionUser, connectionPassword);
Statement constat = conn.createStatement();
String query = "INSERT INTO customers (customer_id, email, deliverable, create_date) VALUES (" + customer.id + ", " + customer.emailAddress + ", " + customer.deliverable + ", " + customer.createDate + ")" ;
constat.executeQuery(query);
conn.close();
}
catch(SQLException e){
System.out.println(e.toString());
}
}
And I have downloaded mysql-connector-java-5.1.20 and set it in my classpath.
If anyone has any suggestions for how I could correct this error, I would be really grateful!
You have to put MySQL jdbc connector jar library into the classpath.
Then initialize the driver before opening the connection with code like the following :
Class.forName("com.mysql.jdbc.Driver").newInstance();
You will need the corresponding mysql JDBC driver jar in your classpath or loadable by your container. See the doc for ConnectorJ and note the installation instructions.
Try to add mysql-connector-java-5.1.20.jar to Glassfish (or Tomcat) lib folder.
you have also a error in this row
constat.executeQuery(query);
if you want insert some data in data base you have to use this code
constat.executeUpdate(query);

Categories

Resources