Exception : java.lang.ClassNotFoundException on MS Access Database [duplicate] - database

I have created an MS Access database and assigned a DSN to it. I want to access it through my Java application.
This is what I am doing:
public class AccessDbConnection {
public static void main(String[] args) {
System.out.println("**ACCESS DB CONNECTION**");
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // for MS Access ... MS access driver loading
String conURL = "jdbc:odbc:sampleDNS";
Connection con = DriverManager.getConnection(conURL);
Statement statement = con.createStatement();
String qry = "SELECT * FROM Table1";
ResultSet rs = statement.executeQuery(qry);
while(rs.next()) {
String id = rs.getString("ID") ;
String fname = rs.getString("First_Name");
String lname = rs.getString("Last_Name");
System.out.println(id + fname + lname);
}
} catch (ClassNotFoundException ex) {
System.out.println("Classforname Exception!!");
Logger.getLogger(AccessDbConnection.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
System.out.println("DriverManager Exception!!");
Logger.getLogger(AccessDbConnection.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
I am getting the exception at the first line of try block. That is class.forname("..");. Why am I having this Exception?

For Java 7 you can simply omit the Class.forName() statement as it is not really required.
For Java 8 you cannot use the JDBC-ODBC Bridge because it has been removed. You will need to use something like UCanAccess instead. For more information, see
Manipulating an Access database from Java without ODBC

in JDK 8, jdbc odbc bridge is no longer used and thus removed fro the JDK. to use Microsoft Access database in JAVA, you need 5 extra JAR libraries.
1- hsqldb.jar
2- jackcess 2.0.4.jar
3- commons-lang-2.6.jar
4- commons-logging-1.1.1.jar
5- ucanaccess-2.0.8.jar
add these libraries to your java project and start with following lines.
Connection conn=DriverManager.getConnection("jdbc:ucanaccess://<Path to your database i.e. MS Access DB>");
Statement s = conn.createStatement();
path could be like E:/Project/JAVA/DBApp
and then your query to be executed. Like
ResultSet rs = s.executeQuery("SELECT * FROM Course");
while(rs.next())
System.out.println(rs.getString("Title") + " " + rs.getString("Code") + " " + rs.getString("Credits"));
certain imports to be used. try catch block must be used and some necessary things no to be forgotten.
Remember, no need of bridging drivers like jdbc odbc or any stuff.

Setup:
My OS windows 8 64bit
Eclipse version Standard/SDK Kepler Service Release 2
My JDK is jdk-8u5-windows-i586
My JRE is jre-8u5-windows-i586
This how I overcome my error.
At the very first my Class.forName("sun.jdbc.odbc.JdbcOdbcDriver") also didn't work.
Then I login to this website and downloaded the UCanAccess 2.0.8 zip (as Mr.Gord Thompson said) file and unzip it.
Then you will also able to find these *.jar files in that unzip folder:
ucanaccess-2.0.8.jar
commons-lang-2.6.jar
commons-logging-1.1.1.jar
hsqldb.jar
jackcess-2.0.4.jar
Then what I did was I copied all these 5 files and paste them in these 2 locations:
C:\Program Files (x86)\eclipse\lib
C:\Program Files (x86)\eclipse\lib\ext
(I did that funny thing becoz I was unable to import these libraries to my project)
Then I reopen the eclipse with my project.then I see all that *.jar files in my project's JRE System Library folder.
Finally my code works.
public static void main(String[] args)
{
try
{
Connection conn=DriverManager.getConnection("jdbc:ucanaccess://C:\\Users\\Hasith\\Documents\\JavaDatabase1.mdb");
Statement stment = conn.createStatement();
String qry = "SELECT * FROM Table1";
ResultSet rs = stment.executeQuery(qry);
while(rs.next())
{
String id = rs.getString("ID") ;
String fname = rs.getString("Nama");
System.out.println(id + fname);
}
}
catch(Exception err)
{
System.out.println(err);
}
//System.out.println("Hasith Sithila");
}

add these dependecies to your .pom file:
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>2.5.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.healthmarketscience.jackcess</groupId>
<artifactId>jackcess-encrypt</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>net.sf.ucanaccess</groupId>
<artifactId>ucanaccess</artifactId>
<version>5.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
and add to your code to call a driver:
Connection conn = DriverManager.getConnection("jdbc:ucanaccess://{file_location}/{accessdb_file_name.mdb};memory=false");

Make sure you have closed your MSAccess file before running the java program.

Related

Read a csv file in Flink 1.15 using Table API

I'm doing a simple tutorial with flink + java using Table API. What I want to do is really simple - I want to read a csv file from a local filesystem, using a schema and print it out.
The way I'm doing this is this(the code below is compiled from samples from Flink's website tutorial section):
package p1;
import org.apache.flink.table.api.*;
import org.apache.flink.api.java.utils.ParameterTool;
public class CabAggregation {
public static void main(String[] args) throws Exception {
ParameterTool params = ParameterTool.fromArgs(args);
EnvironmentSettings settings = EnvironmentSettings
.newInstance()
.inBatchMode()
.build();
TableEnvironment tableEnv = TableEnvironment.create(settings);
final Schema schema = Schema.newBuilder()
.column("cab_id", DataTypes.INT())
.column("cab_plate", DataTypes.STRING())
.column("cab_make", DataTypes.STRING())
.column("cab_driver", DataTypes.STRING())
.column("active_trip", DataTypes.STRING())
.column("pickup_location", DataTypes.STRING())
.column("target_location", DataTypes.STRING())
.column("num_pass", DataTypes.INT())
.build();
tableEnv.createTemporaryTable("cabs",
TableDescriptor
.forConnector("filesystem")
.schema(schema)
.option("path", "file:///Users/virtual/Downloads/cabs.csv")
.format(FormatDescriptor.forFormat("csv").build())
.build());
Table result = tableEnv.from("cabs").select("*");
result.execute().print();
}
}
Running this gives me this:
Caused by: org.apache.flink.table.api.ValidationException: Could not find any factory for identifier 'filesystem' that implements 'org.apache.flink.table.factories.DynamicTableFactory' in the classpath.
Available factory identifiers are:
blackhole
datagen
print
Now, it seems evident that somehow CSV is not available as a factory identifier. I can't figure out why.
I'm building the project with maven.
You'll be needing these dependencies. Have you added them?
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-connector-files</artifactId>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-csv</artifactId>
<version>${flink.version}</version>
</dependency>

Report builder says Cucumber is not a valid report

I have used below code for creating html reports , this code is present in after class of Junit Runner in a cucumber framework , but am getting error saying cucumber.json is not a valid cucumber report. I am assuming that report builder is trying to get the cucumber.json even before it is created completely,
I kept code in cucumber options to create Json file
#CucumberOptions(features = "features/",
glue = { "report"},
format = {"pretty","json:target/cucumber.json"},
tags = {"#testing" }, monochrome = true)
private void generateReportForJsonFiles(File reportOutputDirectory,
List<String> jsonFiles) {
String jenkinsBasePath = "";
String buildNumber = "1";
String projectName = project.getName();
Configuration configuration = new Configuration(reportOutputDirectory, projectName);
configuration.setParallelTesting(false);
configuration.setJenkinsBasePath(jenkinsBasePath);
configuration.setRunWithJenkins(false);
configuration.setBuildNumber(buildNumber);
ReportBuilder reportBuilder = new ReportBuilder(jsonFiles, configuration);
reportBuilder.generateReports();
}
Below is the error:
File 'target/cucumber.json' is not proper Cucumber report!
you should provide a small example (MCVE) which others can use to reproduce your problem
your code snippet configuration.setParallelTesting(false) and your answer cucumber report version is <version>4.2.0</version> do not match, as the method configuration.setParallelTesting was removed in version 4.1.0
Have a look at this small working snippet (based on the few information you provided).
Assume the following structure
pom.xml
src/main/java/CreateReport.java
src/main/resources/log4j2.properties
src/test/java/TestRunner.java
src/test/java/stepdefs/StepDefinitions.java
src/test/resource/features/demo.feature
pom.xml
...
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.target>1.8</maven.compiler.target>
<!--
info.cukes:cucumber-java:1.2.5 is quite old and has been superseded by
io.cucumber:cucumber-java see: https://mvnrepository.com/artifact/io.cucumber/cucumber-java
-->
<version.cucumber>1.2.5</version.cucumber>
</properties>
<dependencies>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>${version.cucumber}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-junit</artifactId>
<version>${version.cucumber}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.masterthought</groupId>
<artifactId>cucumber-reporting</artifactId>
<version>4.0.0</version>
</dependency>
</dependencies>
...
CreateReport.java
import java.io.File;
import java.util.Arrays;
import java.util.List;
import net.masterthought.cucumber.Configuration;
import net.masterthought.cucumber.ReportBuilder;
public class CreateReport {
private void generateReportForJsonFiles(File reportOutputDirectory, List<String> jsonFiles) {
String buildNumber = "1";
String projectName = "StackOverflow example";
Configuration configuration = new Configuration(reportOutputDirectory, projectName);
configuration.setParallelTesting(false);
// configuration.setJenkinsBasePath(jenkinsBasePath);
configuration.setRunWithJenkins(false);
configuration.setBuildNumber(buildNumber);
ReportBuilder reportBuilder = new ReportBuilder(jsonFiles, configuration);
reportBuilder.generateReports();
}
public static void main(String[] args) {
new CreateReport().generateReportForJsonFiles(new File("target/"),
Arrays.asList("target/cucumber.json"));
}
}
log4j2.properties
status = info
name = PropertiesConfig
appenders = console
appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = [%level] %m%n
rootLogger.level = info
rootLogger.appenderRefs = stdout
rootLogger.appenderRef.stdout.ref = STDOUT
TestRunner.java
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
#RunWith(Cucumber.class)
#CucumberOptions(
features = {"src/test/resource/features"},
glue = {"stepdefs"},
plugin = {"json:target/cucumber.json"}
)
public class TestRunner {
}
StepDefinitions.java
package stepdefs;
import org.junit.Assert;
import cucumber.api.java.en.Given;
public class StepDefinitions {
#Given("^a successful step$")
public void aSuccessfulStep() throws Throwable {
System.out.println("a successful step");
}
#Given("^a not successful step$")
public void aNotSuccessfulStep() throws Throwable {
System.out.println("a not successful step");
Assert.fail();
}
}
demo.feature
Feature: Test cucumber reporting plugin
Scenario: Run a non failing scenario
Given a successful step
Scenario: Run a failing scenario
Given a not successful step
run the Cucumber test (this creates the target/cucumber.json file)
$ mvn clean test
run the report creator (
$ mvn exec:java -Dexec.mainClass=CreateReport
...
12:55:21 [INFO] --- exec-maven-plugin:1.6.0:java (default-cli) # cuke-test23.so ---
Dec 18, 2018 12:55:22 PM net.masterthought.cucumber.ReportParser parseJsonFiles
INFO: File 'target/cucumber.json' contains 1 features
the report is generated in target/cucumber-html-reports/overview-features.html

GcsServiceFactory.createGcsService leads to 500 server error

I am working on an app which uses GAE and GCS serverside. Among other things I can upload pictures and store their publicUrl in a google mysql database. Today I tried to use .secureUrl(true) when getting those publicUrls and since then I get a 500 server error when sending post requests.
I can break it down to the following code snippet:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException,
ServletException {
// create Writer for response
PrintWriter out = response.getWriter();
response.setContentType("application/json");
// create Database Connection url with name database, username and password
String mysqlUrl = System.getProperty("cloudsql");
// get 'operation' parameter to determine further action
String operation = request.getParameter("operation");
if (operation == null){ operation = "getFav"; }
GcsService gcsService = GcsServiceFactory.createGcsService();
When I dont comment out the last line where gcsService is set, every post request sent from my phone is answered with a 500 server error. If I make the line a comment, everything (except for the parts where gcs is used) works perfectly. Checking out the Google console, I get the following message:
java.lang.NoClassDefFoundError: com/google/appengine/api/utils/SystemProperty
at com.google.appengine.tools.cloudstorage.GcsServiceFactory.createRawGcsService (GcsServiceFactory.java:57)
at com.google.appengine.tools.cloudstorage.GcsServiceFactory.createGcsService (GcsServiceFactory.java:44)
at com.google.appengine.tools.cloudstorage.GcsServiceFactory.createGcsService (GcsServiceFactory.java:40)
at net.xyz.yzxI.HelloAppEngine.<init> (HelloAppEngine.java:69)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0 (Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance (NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance (DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance (Constructor.java:423)
at java.lang.Class.newInstance (Class.java:443)
at org.eclipse.jetty.server.handler.ContextHandler$Context.createInstance (ContextHandler.java:2481)
at org.eclipse.jetty.servlet.ServletContextHandler$Context.createServlet (ServletContextHandler.java:1327)
at org.eclipse.jetty.servlet.ServletHolder.newInstance (ServletHolder.java:1285)
at org.eclipse.jetty.servlet.ServletHolder.initServlet (ServletHolder.java:615)
at org.eclipse.jetty.servlet.ServletHolder.getServlet (ServletHolder.java:499)
at org.eclipse.jetty.servlet.ServletHolder.ensureInstance (ServletHolder.java:791)
at org.eclipse.jetty.servlet.ServletHolder.prepare (ServletHolder.java:776)
at org.eclipse.jetty.servlet.ServletHandler.doHandle (ServletHandler.java:579)
at org.eclipse.jetty.server.handler.ScopedHandler.handle (ScopedHandler.java:143)
at org.eclipse.jetty.security.SecurityHandler.handle (SecurityHandler.java:524)
at org.eclipse.jetty.server.session.SessionHandler.doHandle (SessionHandler.java:226)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle (ContextHandler.java:1180)
at org.eclipse.jetty.servlet.ServletHandler.doScope (ServletHandler.java:512)
at org.eclipse.jetty.server.session.SessionHandler.doScope (SessionHandler.java:185)
at org.eclipse.jetty.server.handler.ContextHandler.doScope (ContextHandler.java:1112)
at org.eclipse.jetty.server.handler.ScopedHandler.handle (ScopedHandler.java:141)
at com.google.apphosting.runtime.jetty9.AppVersionHandlerMap.handle (AppVersionHandlerMap.java:297)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle (HandlerWrapper.java:134)
at org.eclipse.jetty.server.Server.handle (Server.java:534)
at org.eclipse.jetty.server.HttpChannel.handle (HttpChannel.java:320)
at com.google.apphosting.runtime.jetty9.RpcConnection.handle (RpcConnection.java:202)
at com.google.apphosting.runtime.jetty9.RpcConnector.serviceRequest (RpcConnector.java:81)
at com.google.apphosting.runtime.jetty9.JettyServletEngineAdapter.serviceRequest (JettyServletEngineAdapter.java:108)
at com.google.apphosting.runtime.JavaRuntime$RequestRunnable.dispatchServletRequest (JavaRuntime.java:680)
at com.google.apphosting.runtime.JavaRuntime$RequestRunnable.dispatchRequest (JavaRuntime.java:642)
at com.google.apphosting.runtime.JavaRuntime$RequestRunnable.run (JavaRuntime.java:612)
at com.google.apphosting.runtime.JavaRuntime$NullSandboxRequestRunnable.run (JavaRuntime.java:806)
at com.google.apphosting.runtime.ThreadGroupPool$PoolEntry.run (ThreadGroupPool.java:274)
at java.lang.Thread.run (Thread.java:745)
It drives me crazy: Even if I dont use the gcs at all, just trying to set it up breaks the app. I have like no clue where to look at, so hopefully someone else has had similar experiences or knows what to check.
Thanks in advance
If you are using Maven to handle dependencies this error may be due to a "provided" in the com.google.appengine dependency. Remove that line in pom.xml so Maven will include app engine sdk in the compiled project.
Before:
<dependency>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-api-1.0-sdk</artifactId>
<version>1.9.63</version>
<scope>provided</scope>
</dependency>
After:
<dependency>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-api-1.0-sdk</artifactId>
<version>1.9.63</version>
</dependency>

JAX-RS client returns entity of null

I have a JAX-RS service defined like this:
#Produces(MediaType.APPLICATION_JSON)
#GET
#Path("/namestartswith")
public List<ProductBrand> nameStartsWith(#QueryParam("name") String name) {
List<ProductBrand> productBrandList = productBrandService.findByNameStartsWith(name);
System.out.println("productBrandList: " + productBrandList);
return productBrandList;
}
Issuing the following URL:
http://localhost:19191/productbrand/namestartswith?name=f
produces:
{"productBrand":[{"brandImage":"ffbrand.png","description":"the brand called ff","id":"1","name":"ffbrand"},{"brandImage":"flfl.png","description":"flfl","id":"6","name":"flfl"},{"brandImage":"ffbran.png","description":"ffbr","id":"16","name":"ffbran"}]}
which means the service is working as intended.
Now I use RestEasy for client access.
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-client</artifactId>
<version>${resteasy.version}</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jackson-provider</artifactId>
<version>${resteasy.version}</version>
</dependency>
The following code accesses the service:
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:19191/productbrand/namestartswith?name=" + name);
Response restEasyResponse = target.request(MediaType.APPLICATION_JSON).get();
log("entity: " + restEasyResponse.readEntity(new GenericType<List<ProductBrand>>() {
}););
The output is:
entity: null
Even calling restEasyResponse.getEntity() returns null. What might be wrong?
I had a similar issue and I work around it using:
restEasyResponse.readEntity(List.class)
It will return a List<Map<String, Object>> where each item represents an element of the json array.

Is there a JDBC 4.1 driver for DB2?

Does DB2 (LUW) support JDBC 4.1?
From where can I download this driver if it exist?
The db2 driver for JDBC v3 is called db2jcc.jar
For version 4, the JDBC driver for DB2 is called db2jcc4.jar, and the documentation says: JDBC 4.0 or later functions.
Your question is specific for JDBC 4.1, however the DB2 documentation does not say anything about this JDBC specific release (RowSetProviderClass and auto-close of connection, statement an resultSet)
It does not seem that this jdbc driver is available for this jdbc release.
http://pic.dhe.ibm.com/infocenter/db2luw/v10r5/topic/com.ibm.db2.luw.apdv.java.doc/src/tpc/imjcc_cjvintro.html
List of db2 jdbc drivers: http://www-01.ibm.com/support/docview.wss?uid=swg21363866
As a follow up answer to what #AngocA mentioned above, I developed a simple program to test the DB2 driver to check its compliance level with JDBC.
I found that the first DB2 driver claiming such support is driver 4.13.127.
So any thing after that should also support JDBC 4.1
Here is my simple program you can use to check for the compliance level:
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.SQLException;
public class tester {
// Replace these info with your DB2 info
private final static String hostName = "mydb2.db2.com";
private final static String portNum = "50000";
private final static String userName = "dasusr";
private final static String password = "db2sdin";
private final static String dbName = "mydb";
private final static String fullURL = "jdbc:db2://" + hostName + ":" + portNum
+ "/" + dbName + ":" + "user=" + userName
+ ";password=" + password + ";";
public static void main(String[] args) {
Connection con = null;
try {
con = DriverManager.getConnection(fullURL);
DatabaseMetaData conMD = con.getMetaData();
String driverName = conMD.getDriverName();
String driverVersion = conMD.getDriverVersion();
String jdbcVersion = conMD.getJDBCMajorVersion()
+"."+ conMD.getJDBCMinorVersion();
System.out.println("driverName: " + driverName + "\n"
+"driverVersion: "+ driverVersion + "\n"
+"jdbcVersion: "+ jdbcVersion);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
In your .classpath which would look like this in the Navigator tab in eclipse:
add the location of the driver you would like to test like this:
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse
.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"/>
<!-- driver_4.13.127 -->
<classpathentry kind="lib" path="driver_4.13.127/db2jcc_license_cisuz.jar"/>
<classpathentry kind="lib" path="driver_4.13.127/db2jcc4.jar"/>
<classpathentry kind="output" path="bin"/>
</classpath>
You should then get an output similar to this:
driverName: IBM Data Server Driver for JDBC and SQLJ
driverVersion: 4.13.127
jdbcVersion: 4.1

Resources