Get the Database name through JDBC with UCanAccess - java

EDIT:
I was testing out this code that I found in another post to look for the database name:
public static String getDBname(Connection conn) {
String result = null;
int i = 0;
try {
ResultSet rs = conn.getMetaData().getCatalogs();
while (rs.next()) {
System.out.println(rs.getString(i));
i ++;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
However it just returns me this error:
net.ucanaccess.jdbc.FeatureNotSupportedException: Feature not supported.
at net.ucanaccess.jdbc.UcanaccessDatabaseMetadata.getCatalogs(UcanaccessDatabaseMetadata.java:310)
Is there another way to do this?

For UCanAccess, the "database name" is just the name of the .accdb or .mdb file. That can be retrieved by extracting it from the connection URL as returned by
conn.getMetaData().getURL()
e.g.,
jdbc:ucanaccess://C:/Users/Public/UCanAccessTest.accdb;memory=false

Related

How to use ResultSet returned by java method in SOAPUI with groovy script?

We have created jar file for a java method and imported it in SOAPUI. We are able to call method, however not able to retrieve query result returned in ResultSet by java method in groovy script def dataRow = GetData.GetRecords(preQuery). I am new to groovy script.
Below is method we have written in java and created jar for it.
package getRecords;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class GetData {
protected static Connection con = null;
protected static Statement stmt = null;
protected static ResultSet result = null;
//Opening DB connection
public static void OpenDBConnection(String dbUrl, String driver, String username, String password){
//Making connection to DB
try {
Class.forName(driver);
con = DriverManager.getConnection(dbUrl, username, password);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//Closing DB connection
public static void CloseDBConnection(){
try {
//Closing DB connection
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//Executing query and fetching data from DB
public static ResultSet GetRecords(String query){
//Executing query and saving result into result set
try {
stmt = con.createStatement();
result = stmt.executeQuery(query);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public static void main(String args[]){
System.out.println("DBConnection..");
GetData gd = new GetData();
GetData.OpenDBConnection("jdbc:oracle:thin:#test:1530/test", "oracle.jdbc.driver.OracleDriver", "******", "******");
System.out.println("DB");
}
}
I suspect your result set is being closed when you return from GetRecords (tip: use camel case for Java method names, starting with a lower-case character) and you may also be jumping JVMs. See also Is it Ok to Pass ResultSet?.
You probably don't need to use your result set as a result set back in soapUI, you just want the data, so a better option would be to populate a bean and return a List of those instead:
public static List<MyBean> GetRecords(String query){
List<MyBean> myBeans = new ArrayList<>();
//Executing query and saving result into result set
try {
stmt = con.createStatement();
result = stmt.executeQuery(query);
while (result.next()) {
MyBean myBean = new MyBean();
// Populate the bean...
myBeans.add(myBean);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return myBeans;
}
You might also want to investigate the try-with-resources feature that came out with Java 7: it'll handle the closing of your connections automatically.
In SoapUi you can directly do the JDBC call using Groovy scripting.
If you wanted to do some Database operation in soapUI you can write the code in groovy using the corresponding database driver ( DB2, Oracle, Mysql), Until or unless any specific reason to use jar file as you have mentioned.
Making the database connection you need to download and place the jar files inside ( SoapUi install folder/bin/ext
eg.. for Oracle (ojdbc6.jar, orai18n.jar)

Trouble retrieving data with JDBC in Eclipse IDE

I am pretty new to Java so I'm working on a project to develop my knowledge with databases and Java.
I have figured out how to add queries into the database but now I'm getting errors when trying to print them out.
Assume I already have everything that's necessary imported in such as the scanner and sql statements
Here is my connection class which is named MainClass:
public static Connection getConnection() throws Exception {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/testTable";
String username = "placeholder";
String password = "placeholder";
Class.forName(driver);
Connection conn = Driver Manager.getConnection(url, username, password);
return conn;
}
Now in a different class if the user types !lookup and a word I want the definition of that word to be retrieved from the table whose name is dictionary and columns are word, definition:
String userSearch = user_input.next();
String[] userSearchSplit = userSearch.split(" ", 3);
if (userSearchSplit[0].equals("!lookup")) {
try {
conn = MainClass.getConnection();
String query = "select definition from dictionary where word=" + userSearchSplit[1];
ResultSet result = pstmt.executeQuery(query);
while (result.next()) {
String definition = result.getString("definition");
System.out.println(definition);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
At the end of all this when I try to look up a word I put in the table before running I get:
java.lang.NullPointerException
Check if your user_input is null?
I am assuming your code:
ResultSet result = pstmt.executeQuery(query);
as
Statement pstmt = conn.createStatement();
ResultSet result = pstmt.executeQuery(query);
Or it could be that you have not initialized the pstmt properly

My ResultSet is always closed when I return it from my method

I have the following class:
public class Refunds {
ResultSet dataToHash = null;
public Refunds (String UrnId) {
Database db = null;
CallableStatement callable;
String query = "select * from testmdb.dbo.ApEdiZcusSaSendFile where SourceID='LAN' and UrnID=?";
// Get database connection
try {
db = new Database("jdbc/refund");
} catch (NamingException | SQLException e1) {
e1.printStackTrace();
}
// Run the query
try {
callable = db.connection.prepareCall(query);
callable.setString(1, UrnId);
dataToHash = callable.executeQuery();
} catch (SQLException s) {
System.out.println("A SQL exception was thrown while running the query: ");
s.printStackTrace();
} catch (Exception e) {
System.out.println("A general exception was thrown while running the query: ");
e.printStackTrace();
} finally {
db.closeConnection();
}
}
public ResultSet getDataToHash() {
return dataToHash;
}
}
And I use it like this:
// Get the result set
Refunds refunds = new Refunds(urnId);
ResultSet dataToHash = refunds.getDataToHash();
However, every single time dataToHash is .closed(). I don't close my ResultSet. Whatever the problem is, how can I modify this code so that when I get it, it won't be closed?
PS - Just ignore my old school System.outs...
You close the connection, and that closes the ResultSet.
Instead of storing the ResultSet in a class member, store it in a local variable inside Refunds, and read all the data from it before returning from the Refunds method and closing the connection.

How to connect with MySql in GWT? (AppEngine)

I've strange problem.
I'm using GWT on AppEngine and I want to create RPC which connect to MySql. All this day I'm sitting on it.. This is my implementation of RPC methods:
java.sql.Connection con = null;
public DataBaseServiceImpl() {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.print("bladd..");
e.printStackTrace();
}
String url ="jdbc:mysql://localhost:8806/base";
try {
con = DriverManager.getConnection( url,"root", "");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public ArrayList<String[]> getTables(int idUser) throws SQLException {
Statement st = con.createStatement();
ResultSet retrive = st.executeQuery("query");
ArrayList<String[]> result = new ArrayList<String[]>();
while(retrive.next())
{
String[] s = new String[2];
int theInt= retrive.getInt("ID__TABLE");
String str = retrive.getString("LABEL");
s[0]=Integer.toString(theInt);
s[1]=str;
result.add(s);
}
return result;
}
And I have this error:
java.sql.SQLException: Unable to initialize driver properties due to
java.lang.IllegalAccessException: Class
com.google.appengine.tools.development.agent.runtime.Runtime can not
access a member of class com.mysql.jdbc.ConnectionPropertiesImpl with
modifiers "private"
I don't have any idea what it is.
Could someone help me?
Regards.
Well the bottom line is you have really messy code. There are many violations to good coding practice.
From the code you included this line never gets executed:
con = DriverManager.getConnection( url,"root", "");
So there is no connection to your db. Does your exception indicate that this line
Statement st = con.createStatement();
is the problem?
I had the same problem running on jre1.7.0_25.
I resolved it by upgrading to jre1.7.0_45.

What should be the connection string while using CQL jdbc driver

What should be the connection string while using CQL jdbc driver?
Will I be able to find a proper/complete example for CQL using CQL JDBC driver in Java online?
You'll need the cql jar from the apache site.
Here's the basic test I used after entering data via CLI (using sample from wiki):
public class CqlJdbcTestBasic {
public static void main(String[] args) {
Connection con = null;
try {
Class.forName("org.apache.cassandra.cql.jdbc.CassandraDriver");
con = DriverManager.getConnection("jdbc:cassandra:root/root#localhost:9160/MyKeyspace");
String query = "SELECT KEY, 'first', last FROM User WHERE age=42";
Statement stmt = con.createStatement();
ResultSet result = stmt.executeQuery(query);
while (result.next()) {
System.out.println(result.getString("KEY"));
System.out.println(result.getString("first"));
System.out.println(result.getString("last"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (con != null) {
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
con = null;
}
}
}
}
The user/password (root/root) seems arbitrary, just be sure to specify the Keyspace (MyKeyspace)
Note, 'first' is quoted in the query string because it is an CQL keyword
You may also try using the cassandra-jdbc driver from http://code.google.com/a/apache-extras.org/p/cassandra-jdbc/.
Alternatively using the following maven dependency:
<dependency>
<groupId>org.apache-extras.cassandra-jdbc</groupId>
<artifactId>cassandra-jdbc</artifactId>
<version>1.2.1</version>
</dependency>

Categories