Ms Access Connect to Java [duplicate] - java

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

Why the error occurs: 'error: package com.mysql does not exist'?

I am trying to link a MySQL database to my Jira plugin. I am using Intellij IDEA Community Edition, and it says the syntax is all good. I have the MySQL Connector .jar in my library (added through File->Project Structure), so it shouldn't be that, unless there is somewhere else I have to add the .jar file that it won't tell me. I had just the MySQL .jar added via downloading from their website and it wouldn't work. I added the maven MySQL .jar and that didn't work. I added both of them and it still doesn't work. My external libraries
I am getting this error when I compile the plugin:
Caused by: org.apache.maven.plugin.compiler.CompilationFailureException: Compilation failure
/C:/Users/USER/dynamicSelectCF/src/main/java/PACKAGE/DatabaseConnection.java:[11,1] package com.mysql does not exist
With this code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import com.mysql.*;
public class DatabaseConnection {
public static ArrayList<String> connection(ArrayList<String> population){
population.clear();
population.add("-------------------");
Connection connection = null;
Statement statement = null;
ResultSet result = null;
String url = Constants.getUrl();
String username = Constants.getUsername();
String password = Constants.getPassword();
String query = "SELECT name, p_o_allowed FROM database WHERE p_o_allowed LIKE 'P%'";
try{
Class.forName("com.mysql.cj.jdbc.Driver");
} catch(ClassNotFoundException e){
population.add("mysql driver a no no");
population.add(e.getMessage());
population.add(e.toString());
e.printStackTrace();
}
population.add("-------------------");
try{
population.add("trying connection");
connection = DriverManager.getConnection(url, username, password);
population.add("trying statement");
statement = connection.createStatement();
population.add("trying result");
result = statement.executeQuery(query);
population.add("all 3 are a go!");
while(result.next()){
population.add(result.getString("name"));
}
}catch (SQLException e){
population.add("Yeah we didn't get in fam");
population.add(e.getMessage());
e.printStackTrace();
}finally{
closeResultSet(result);
closeStatement(statement);
closeConnection(connection);
}
return population;
}
I also have this in my pom.xml file which is directly from the MySQL website.
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.20</version>
<scope>provided</scope>
</dependency>
I know I do not need import com.mysql; however, that is the only way to generate the error on compilation into my terminal otherwise it goes to the try/catch and throws "com.mysql.cj.jdbc.Driver not found by PACKAGE".
If you have any question about the population ArrayList, it is for dynamically populating a Select list for the Jira Plugin. And adding those errors and tests allowed me to see them in my Jira dev website.
You have specified an wrong dependency scope for a mysql-connector-java. The following dependency solves this problem:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.20</version>
<scope>runtime</scope>
</dependency>
More information: Apache Maven: Dependency Scope

JavaFx SQLite driver is not suitable

I am trying to connect to a SQLite database on my local device (Ubuntu).
my setup is VS Code with Maven
The error
java.sql.SQLException: No suitable driver found for jdbc:sqlite:/home/idir/embag/chek/Data/Checks.sql
Database.java, connect method
public void Connect() {
String AbsolutePath = new File("").getAbsolutePath();
path = "jdbc:sqlite:"+ AbsolutePath + DATABASE_PATH + DATABASE_NAME ;
try{
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection(path);
if (conn != null){
DatabaseMetaData meta = conn.getMetaData();
System.out.println("The driver name is " + meta.getDriverName());
System.out.println("A new database has been created.");
}
}
catch(Exception e){
System.out.println(e.toString());
}
}
Maven pom.xml
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.36.0.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.25</version>
</dependency>
Module-info.java
requires java.sql;
requires mysql.connector.java;
What I tried
+3 hours of search with no hope
I fixed the problem by removing the MySQL dependency as pointed out by the previous responses .
Added to the Module-info.java:
requires org.xerial.sqlitejdbc;
Also added this to pom.xml:
<transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
<resource>META-INF/services/java.sql.Driver</resource>
</transformer>
Don’t mix database engines
You are asking your MySQL driver to make a connection using a string meant for SQLite.
MySQL and SQLite are two entirely separate different database engines. So your code makes no sense.
By the way…
In modern Java, there is no need to call Class.forName. JDBC drivers are now automatically loaded via the Java SPI facility.
Generally best to separate your code for configuring the database connection info from the code that accesses the database. Have the first produce a DataSource object that is passed into the second.

Unable to get string of query using driverspy

I am working on a project where I need to log query in Log files and add those queries to my assert statement as well
I have build prepared statements using below driver
net.sf.log4jdbc.sql.jdbcapi.DriverSpy
And url
jdbc:log4jdbc:sybase:Tds ........
Dependencies I am using is as below:
<dependency>
<groupId>net.sourceforge.jtds</groupId>
<artifactId>jtds</artifactId>
<version>1.3.1</version>
</dependency>
PrepareStatement Example:
public void getTest(MyBean bean) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = DatabaseUtil.getDatabaseConnection();
ps = conn.prepareStatement(objTestQueryUtil.getQuery("GET_Test"));
ps.setString(1, bean.getTypeOfTest());
ps.setString(2, bean.getTest());
ps.setString(3, bean.getTestState());
ps.setString(4, bean.getTestStep());
rs = ps.executeQuery();
while(rs.next()) {
bean.setTest(rs.getInt("Test"));
}
}catch (SQLException e) {
AutomationLog.error(e.getMessage(),e);
}finally {
DatabaseUtil.close(conn,ps,rs);
}
}
In my assert class, the sql should see in my assert code like:
Assert.assertTrue("Got Test "+query, true);
Can you please tell me if there any way around by which I can get query in variables in java also, currently query directly logs into the log file and I am not able to find anyway by which I can get them in my script, i.e store on any variable etc
Another dependencies or solution are also welcome if current dependencies do not have such provisions for pre-prepared-statements
This is not the optimal solution but it can solve your problem:
Open your jtds jar file (or download the jtds source files and import them in your IDE), find and decompile the class net.sf.log4jdbc.StatementSpy.class,
add a static String variable in that class, let's call it myLastExecutedSQL
edit the reportSQL() method, assign the sql method parameter to your static variable
compile the new class (or regenerate the jar) and use it in your project
in your test class you will be able to access the last executed query with StatementSpy.myLastExecutedSQL
As you're using maven you will have to replace the jar on the maven home folder
The drawback of this is that you cannot use it in a multi-threaded environment, but it will do the trick.
I hope it's clear enough

JDBC no suitable driver found just on Linux? [duplicate]

This question already has answers here:
Connect Java to a MySQL database
(14 answers)
The infamous java.sql.SQLException: No suitable driver found
(21 answers)
Closed last month.
I am trying to write a program to connect to a MySQL database in eclipse, but I get the error "java.sql.SQLException: No suitable driver found".
The java code is:
import java.sql.*;
public class FirstExample {
//static final String S_JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String S_DB_URL = "jdbc:mysql://localhost:3306/emp";
static final String S_USER = "root";
static final String S_PASS = "root";
public static void main(String[] args) {
try {
System.out.println("Connecting to database...");
//Class.forName(S_JDBC_DRIVER);
Connection connection = DriverManager.getConnection(S_DB_URL,
S_USER, S_PASS);
System.out.println("Creating statement...");
Statement statement = connection.createStatement();
String sql = "SELECT * FROM Employee";
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
int iId = resultSet.getInt("id");
int iAge = resultSet.getInt("age");
String sFirst = resultSet.getString("fname");
String sLast = resultSet.getString("lname");
System.out.print("ID: " + iId);
System.out.print("\tAge: " + iAge);
System.out.print("\tFirst: " + sFirst);
System.out.println("\tLast: " + sLast);
}
resultSet.close();
statement.close();
connection.close();
} catch (SQLException se) {
for (Throwable t : se) {
t.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}
The output in the console tab is:
Connecting to database...
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/emp
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at FirstExample.main(FirstExample.java:21)
Goodbye!
I have used the MySQL Connector/J. It is unzipped in the MySQL installation directory and the jar file is added to the CLASSPATH.
Also refer to this image. There is an ! mark at the project root.image01
I get the error as in the next image: image02 when I include the 2 commented statements:
static final String S_JDBC_DRIVER = "com.mysql.jdbc.Driver";
Class.forName(S_JDBC_DRIVER);
For all but the most trivial applications the CLASSPATH environment variable is NOT used. Normally the libraries are include in the Class-Path entry in the manifest of the jar, or in the -cp option of the java commandline.
In this case you need to add the MySQL JDBC driver to the buildpath of your Eclipse project.
I had the same problem. I solved it by adding:
Class.forName("com.mysql.jdbc.Driver");
you can place the path like java -cppwd/mysql-connector-java-5.1.22-bin.jar:. <classname>.
make sure that your in same directory where the mysql driver is .
Hope that helps .
Load Driver class just before getting the connection.
Use this code:
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test_db", "user", "passw");
Alternatively you can also add the installed jar file to your eclipse project by selecting the project in eclipse, right click it and go down to properties, select the Java Build Path>>select the Libraries Tab>>Add external jar file and browse for the installed mysql-connector-java.jar file or any mysql java connector file int the /usr/share/java/ directory for most ubuntu users. Click okay and rebuild your project. Good luck
I encountered the same problem as you, but I handled it as follows:
I copied the jar, which is called mysql-connector-java-5.1.23-bin.jar, into the \Apache Software Foundation\Tomcat 6.0\lib, and restarted tomcat.
Hope that helps

Connecting JDBC with Firebirdsql

I had a problem in connecting with the firebirdsql.
here is my code.
try {
Class.forName("org.firebirdsql.jdbc.FBDriver");
Connection con= DriverManager.getConnection("jdbc:firebirdsql:localhost/3050:C:\\EMPLOYEE.FDB","sysdba","masterkey");
Statement stm= con.createStatement();
ResultSet res= stm.executeQuery("SELECT * FROM Emp");
while (res.next()) {
System.out.println("EMPLOYEE NAME:"
+ res.getString("NAME"));
}
} catch (Exception e) {
System.out.println(e);
}
Getting an ERROR like.
java.lang.ClassNotFoundException: org.firebirdsql.jdbc.FBDriver
The java.lang.ClassNotFoundException: org.firebirdsql.jdbc.FBDriver indicates that you do not have Jaybird (the Firebird JDBC driver) on your class path, as Java failed to load the driver class.
You can download Jaybird from https://www.firebirdsql.org/en/jdbc-driver/
You need to make sure that jaybird-full-2.2.12.jar (or jaybird-2.2.12.jar and lib/connector-api-1.5.jar) are on the class path when you run the application.
This means that you either need to include it in the manifest, or you need to explicitly specify it when running Java:
java -cp .;jaybird-full-2.2.12.jar MyClass
Alternatively, if you use Maven, you can include the dependency using:
<dependency>
<groupId>org.firebirdsql.jdbc</groupId>
<artifactId>jaybird-jdk18</artifactId>
<version>2.2.12</version>
</dependency>
See also the Jaybird JDBC Driver Java Programmer's Manual, specifically chapter 2.
The use of Class.forName("org.firebirdsql.jdbc.FBDriver"); is not necessary with Jaybird 2.2 and higher.

Categories