Nothing happening when reading .accdb database - java

I am trying to create a program that will read a database and output it. I have followed the tutorial at http://www.codeproject.com/Articles/35018/Access-MS-Access-Databases-from-Java. But when I run my program, nothing happens. Not even errors...
I probably have missed something, but I don't know what it could be. Here's my code:
import java.sql.*;
public class ReadDB {
public static void ReadDB() {
try{
//Source: http://www.codeproject.com/Articles/35018/Access-MS-Access-Databases-from-Java
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=ratingdb.accdb;";
Connection conn = DriverManager.getConnection(database, "", "");
Statement s = conn.createStatement();
//Read Table
String selTable = "SELECT * FROM RATINGS";
s.execute(selTable);
ResultSet rs = s.getResultSet();
while((rs!=null) && (rs.next()))
{
System.out.println(rs.getString(1) + " : " + rs.getString(2));
}
s.close();
conn.close();
} catch(Exception e){
System.out.println ("Unable to connect to the database");
System.out.println ("Exception: " + e.getMessage());
}
}
}
After Black Panther's comment, I got this error:
java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver]General error Unable to open registry key Temporary (volatile) Ace DSN for process 0x13f4 Thread 0x1204 DBC 0x42170d4
EDIT: A new error occured: Exception: [Microsoft][ODBC Microsoft Access Driver] Not a valid file name. Does this mean that the driver I use does not exist?

Even if it throws the exceptions you wouldn't be able to see them because you have handled the errors in a wrong way. You shouldn't just catch the exceptions and move on. That defies the whole concept of exception handling.
You should do something like this for your exceptions to be printed in the console.
try {
//code that throws exceptions
} catch(Exception e) {
e.printStackTrace(); //prints the error to the console and you missed it
}
EDIT:
It seems you are having some permissions issue.
An Excerpt from the site http://support.sas.com/kb/40/228.html
This problem occurs for several reasons, including not having permissions on an ODBC registry key. In such a case, change the permissions on the registry key as follows:
Start the registry editor using the regedit command:
select Start ► Run and enter regedit.
If your SAS PC Files Server is on a 64-bit machine, expand the following key:
HKEY_LOCAL_MACHINE ► SOFTWARE ► WOW6432NODE ► ODBC.
If your SAS PC Files Server is on a 32-bit machine, expand the following key:
HKEY_LOCAL_MACHINE ► SOFTWARE ► ODBC.
Right-click the ODBC folder and select Permissions.
Make sure that the logon ID that is running the SAS process has full control.
The problem might also occur due to older ODBC drivers from Microsoft, particularly from Office 2007.
To install the newer ODBC drivers, go to Microsoft Access Database Engine 2010 Redistributable.
If you have 32-bit Microsoft Office, download the AccessDatabaseEngine.exe file.
Download the other ODBC driver only if you have 64-bit version of Microsoft Office.
If you are trying to create an .mdb file and use it then do this
go to
File -> Options -> General, and set the Default File Format to Access 2002-2003
And change your database URL to
"jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=ratingdb.mdb;";
to use the .mdb file.
To use an .accdb file try doing this,
"jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=ratingdb.accdb;";

Related

Java JDBC Driver stops working after initial execution [duplicate]

This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 1 year ago.
I am currently making a backend reporting system (for a voting system assignment) using Java on VS Code, I am connecting to a MySQL database using the JDBC library in order to do calculations and stats and so on. So what happens is that once I create a project file and include the mysql-connector-java-8.0.25.jar in the referenced libraries, I can connect to the DB and retrieve data from the tables just fine, but after a few executions I no longer get output and it shows me the error "java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver".
Can anyone tell me why this is happening and how to fix this? There are no changes that I know of taking place in the Environment Variables (at least from what I can see in Windows path list) unless something is being overwritten somewhere or that it's a bug of some sort. Any advice would be greatly helpful, I've been unable to figure this out all day
This is what my ReportSystem.java looks like...
import java.sql.*;
public class ReportSystem
{
public static void main(String[] args)
{
//Test driver connection/registration
try
{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ElectionDB","<username>","<password>");
Statement stmt = conn.createStatement();
ResultSet result = stmt.executeQuery("SELECT * FROM ElectionDB.Votes");
int typeColumn = 1;
int districtColumn = 2;
//Output results line by line
while(result.next())
{
System.out.println(result.getString(typeColumn));
System.out.println(result.getString(districtColumn));
}
//Remember to close the connection
conn.close();
}
catch (Exception e)
{
System.out.println(e);
}
}
}
My file structure as in the directory is as follows:
ReportSystem
>src > ReportSystem.java
> ReportSystem.class
>lib
>.vscode > settings.json
The JRE system library used is: [jdk-16.0.1]
The Referenced Libraries contains: [mysql-connector-java-8.0.25.jar]
Screenshot for context Project Setup in VS Code
I'm able to get result after running code 20 times continuously by clicking the run button. The only difference is the JDBC connection string, which is copied directly by right clicking the MYSQL connection:
So in my project, the connection string is like:
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/?user=username","<username>","<password>");
OR
You could try
String url="jdbc:mysql://localhost:3306/ElectionDB?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC"
For your reference, OS Infomation:
MySQL: 8.0 // mysql-connector-java-8.0.25.jar
VSCode: 1.56.2 //
java.home: JDK16 // Debugger for Java: 0.33.1

DB2 external java jar file stored procedure error

I have been trying to call a java jar file from DB2 stored procedure as external jar.
Below is my external jar file code.
package connection;
public class Connect {
static Connection con = null;
static Statement stmt = null;
public static void main(String[] args) throws SQLException {
javastp("v1");
}
public static void javastp( String name) throws SQLException{
try {
con = DriverManager.getConnection( "jdbc:default:connection" );
stmt = con.createStatement();
stmt.executeUpdate("INSERT INTO SCHEMA_NAME.TEST(NAME, FLAG) VALUES ('"+name+"',true) ");
}catch (Exception e) {
// ...
}finally {
//Close open resources
if (stmt != null) stmt.close();
if (con != null) con.close();
}
}
}
i install it using below command in db2 server
db2 call sqlj.install_jar('file:E:/jarpath../jarname.jar','jarname',0);
Below is the stored procedure for DB2 external jar.
CREATE OR REPLACE PROCEDURE SCHEMA_NAME.PROC6()
LANGUAGE java
PARAMETER STYLE java
FENCED
EXTERNAL NAME 'jarname:connection.Connect.main'
The stored procedure executes successfully without errors.
But when i try to call the stored procedure using below,
CALL SCHEMA_NAME.PROC6()
i get the below error
SQL Error [38503]: A stored procedure process has been terminated abnormally. Routine name: "SCHEMA_NAME.PROC6". Specific name: "SQL201016144125554".. SQLCODE=-1131, SQLSTATE=38503, DRIVER=4.8.86
The java jar works fine when executed directly in the command prompt and the records are being inserted into the table, but i cant seem to figure out why the external stored procedure gives me error when i try to call it that way.
Can somebody here please help me out as am stuck on this since a very long time and i have no background of DB2.
the db2level command gives the below output:
DB21085I This instance or install (instance name, where applicable: "DB2")
uses "64" bits and DB2 code release "SQL10058" with level identifier
"0609010E".
Informational tokens are "DB2 v10.5.800.381", "s160901", "IP24000", and Fix
Pack "8".
Product is installed at "C:\PROGRA~1\IBM\SQLLIB" with DB2 Copy Name "DB2COPY1".
Linux Suse db2 version 11.1.2
Database server = DB2/LINUXX8664 11.1.2
The log is as below:
2020-10-20-09.24.56.746633+330 I4952989679E1230 LEVEL: Error
PID : 31693 TID : 140179352315648 PROC : db2sysc 0
INSTANCE: NODE : 000 DB :
APPHDL : APPID:
AUTHID : HOSTNAME:
EDUID : 2768 EDUNAME: db2agent () 0
FUNCTION: DB2 UDB, routine_infrastructure, sqlerWaitForFencedInvocation, probe:12115
MESSAGE : ZRC=0xFFFFFB38=-1224
SQL1224N The database manager is not able to accept new requests,
has terminated all requests in progress, or has terminated the
specified request because of an error or a forced interrupt.
Error SQL1131N has the following description
The DB2 architecture is designed so that applications run in a different address space than the database server. Running applications in a different address space prevents application programming errors from overwriting database manager internal buffers or files, and prevents application errors from crashing the database manager. The fenced mode process (db2fmp) is responsible for executing fenced stored procedures and user-defined functions in a different address space than the database server.
This message is returned when the db2fmp process terminates abnormally while running the named routine. The db2fmp process could have terminated abnormally for many reasons, including the following reasons:
There was a coding error, such as division by zero or an out-of-bounds pointer reference, in the implementation of the stored procedure or user-defined function that the db2fmp process was executing.
Another process terminated the db2fmp process using a signal, such as the termination signal SIGTERM.
SQLJ.INSTALL_JAR failed while installing a Java routine because the fenced user does not have permission to create or write to the necessary directories on the server.
Db2 is unforgiving when you make mistakes with external non-SQL code, in this case, it just throws an exception and expects you to sort it out.
Only use java for Db2 stored procedures when there is a compelling reason to NOT use SQL PL procedures.
You have these mistakes
You cannot use a main() for a Db2 java stored procedure entry point
The stored procedure entry point should be in your case the javastp() method
The EXTERNAL NAME clause in the DDL must not reference main() but should use javastp instead
The parameters in the create procedure line must match those of the method
in number and type and sequence. (In your case that is (IN name varchar(255) or similar).

Why I obtain this SQLException (No suitable driver) when I try to create a Connection object for an Oracle database?

I have to create a very simple batch Java application (an application that run into shell) and that perform some query on an Oracle database using JDBC and I never done it.
I am following this tutorial: http://www.ntu.edu.sg/home/ehchua/programming/java/JDBC_Basic.html
So I have done in this way to allocate a new Connection object for my application:
import java.sql.*;
public class Main {
public static void main(String[] args) {
System.out.println("Hello World !!!");
String partitaIVA = args[0];
String nomePDF = args[1];
Connection conn = null;
Statement stmt = null;
try {
// Step 1: Allocate a database "Connection" object
conn = DriverManager.getConnection("jdbc:oracle:thin:#XXX.XXX.XXX.XXX:1521:eme1", "myUserName", "myPswd"); // Oracle DB
} catch(SQLException ex) {
ex.printStackTrace();
}
}
}
The problem is that when I run the application it seems that the SQLException is thrown because enter into the catch block and print the following error message in the console:
java.sql.SQLException: No suitable driver found for jdbc:oracle:thin:#XXX.XXX.XXX.XXX:1521:eme1
at java.sql.DriverManager.getConnection(DriverManager.java:602)
at java.sql.DriverManager.getConnection(DriverManager.java:185)
at Main.main(Main.java:16)
Why? What cause this problem and how can I fix this issue? What am I missing?
Tnx
You need to have an appropriate ojdbc.jar in you classpath. E.g. see Oracle JDBC ojdbc6 Jar as a Maven Dependency
The problem should be that the linked tutorial describes how to connect to a Mysql, but you're trying to connect to an oracle - therefore you need the oracle driver in your classpath.
How about following oracle's documentation for its Driver. http://docs.oracle.com/cd/E11882_01/appdev.112/e13995/oracle/jdbc/OracleDriver.html
In the above code, you didn't registered the driver class.
Class.forName ("oracle.jdbc.OracleDriver");
If you are following instructions from the given link.
In chapter 2.2 you have instructions how to instal MySql drivers.
If you are using an Oracle database, then you'll need to instal Oracle JDBC drivers.
If you don't want affect your JDK installation like in tutorial, you can load driver dynamicaly

How do I create a H2 database inside a java project in Eclipse?

I want to create an embedded H2 database in my simple java project in Eclipse. How do I do this programatically and package the db inside my code ? I tried a SO post for this
and got an error in my code.
Code -
public static void main(String[]args){
JdbcDataSource ds = new JdbcDataSource();
ds.setURL("jdbc:h2:˜/test");
ds.setUser("sa");
ds.setPassword("sa");
try {
Connection conn = ds.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
}
Error -
org.h2.jdbc.JdbcSQLException: A file path that is implicitly relative to the
current working directory is not allowed in the database URL "jdbc:h2:˜/test".
Use an absolute path, ~/name, ./name, or the baseDir setting instead. [90011-181]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
at org.h2.message.DbException.get(DbException.java:179)
at org.h2.message.DbException.get(DbException.java:155)
at org.h2.engine.ConnectionInfo.getName(ConnectionInfo.java:398)
at org.h2.engine.Engine.openSession(Engine.java:45)
at org.h2.engine.Engine.openSession(Engine.java:167)
at org.h2.engine.Engine.createSessionAndValidate(Engine.java:145)
at org.h2.engine.Engine.createSession(Engine.java:128)
at org.h2.engine.Engine.createSession(Engine.java:26)
at org.h2.engine.SessionRemote.connectEmbeddedOrServer(SessionRemote.java:347)
at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:108)
at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:92)
at org.h2.Driver.connect(Driver.java:72)
at org.h2.jdbcx.JdbcDataSource.getJdbcConnection(JdbcDataSource.java:190)
at org.h2.jdbcx.JdbcDataSource.getConnection(JdbcDataSource.java:161)
at MyCode.main(MyCode.java:8)
I saw this link - https://groups.google.com/forum/#!msg/h2-database/SlSwte0DLSU/eWj0UaejdkEJ and Where are my H2 database files?. Its not clear how I can get the exact path to test database on my windows pc.
How do I first access the test database and then create another database inside my java project ?
Thank you.
You have used the wrong character. You need to use ~ (tilde) and you have use ˜ (I don't know what it is, but it's not a tilde).
The location of the H2 files is very nicely documented. To view the contents, execute the h2.jar. It is not only the driver, but also an executable that will start a web-based applications for DB management.

Unable to add odbc5.jar in classpath

I want to connect to the oracle DB using Play Framework 1.2.5. FOr this I have modified the application.conf file as follows:
db.url=jdbc:oracle:thin:#localhost:1521/orcl
db.driver=oracle.jdbc.OracleDriver
db.user=system
db.pass=tiger
Then I tried to add the driver i.e. classes12.jar/odbc5.jar but everytime when i try to run it, I am getting the exception:
Cannot connect to the database, Driver not found
For adding the jar file in Eclipse IDE, below are the steps I tried:
1) Added it in the lib folder (present under the root directory of my new application) and then added it to the java build path
2) Added it in the framework/lib folder (inside the downloaded framework folder) and then added it to the java build path
In both the cases, I am getting the above mentioned exception.
Also, Please list down the steps for connection to an oracle db, I am not able to find it anywhere in the documentation
EDIT
I am able to add the jar in the classpath, everything was fine except that I did not restarted the server once it failed to connect the jar.
I did this code for fetching some data from the database:
Connection conn = DB.getConnection();
PreparedStatement stmt = null;
System.out.println(conn);
try {
stmt = conn.prepareStatement("select dept_id from emp where emp_id = 11");
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
System.out.println("Dept Id: " + rs.getInt("dept_id"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This approach is working but I am having a confusion:
If I comment the entire block of code and run the application then I can see the message in the console stating the connection is made to the DB. Hence :
1) Is the above block of code the right approach to fetch the data from Oracle DB or something better than this is present?
2) Is it like for the entire application lifetime, the connection with tht DB will persist?
I am a newbie in this, hence struggling :(
Please let me know hoe to proceed with this.
Regards
Oracle db driver class name is oracle.jdbc.driver.OracleDriver

Categories

Resources