Using class.ForName to load ucanaccess in a maven project - java

Using class.ForName to load ucanaccess in a maven project
OK so I am now totally out of my depth. Everything was going so well before I started to use Maven and now its so much more complicated.
Anyway I am trying to connect to a database using ucanaccess.
public Statement ConnectorNoInsert(String HospNum,String SName,String FName,String DOB) throws SQLException{
Preferences userPrefs = Preferences.userNodeForPackage(main.java.Console.TBB_SQLBuilder.class);
String connectDB ="jdbc:ucanaccess://"+userPrefs.get("PathForDB", null);
System.out.println("Connection To Database Made "+userPrefs.get("PathForDB", null));
Connection conn=DriverManager.getConnection(connectDB);
Statement st =conn.createStatement();
return st;
The error that I get is:
ERROR: java.sql.SQLException: No suitable driver found for jdbc:ucanaccess://PhysJava/Physiology.mdb
so I added Class.forName("net.ucanaccess.jdbc.UcanaccessDriver"); above the Connection conn line. This gives me the error:
unreported exception java.lang.ClassNotFoundException; must be caught or declared to be thrown and the project doesnt compile
I suppose the question is: how to call Class.forName("net.ucanaccess.jdbc.UcanaccessDriver"); in a maven project. If I need to use a ClassLoader could someone please show me how

The first one ("No suitable driver") is a run-time error, the second one ("unreported exception") a compile-time one. The error message is pretty explicit: "...must be caught or declared to be thrown..." Fix the code in this sense.

Related

Trying to run SQL statements in the Main of a Java application [duplicate]

This question already has answers here:
No suitable driver found for jdbc mysql? [duplicate]
(6 answers)
Closed 3 years ago.
I've successfully connected to the database through intellij, but I can't figure out how to run sql statements in the main. I have a database class that can run all of the SQL statements but can't get it to work as if I were to write functions that can insert and delete.
public static void main (String[] args)
{
Connection conn;
{
try {
conn = DriverManager.getConnection("jdbc:mysql://35.247.87.196:4406","username","password");
Statement stmt=conn.createStatement();
String strselect="select * from EmployeeTable";
System.out.println("The sql statement is: "+strselect+"\n");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
and I get the exception
java.sql.SQLException: No suitable driver found for jdbc:mysql://35.247.87.196:3306
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:702)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
at DataGenerator.main(DataGenerator.java:30)
Out of the box, java doesn't support any databases. You need to plug in drivers for database engines in order to make it work.
How do you do that? Just make sure the 'JDBC driver' is on the classpath. There is no need to do anything but that. So, find the JDBC driver for your db engine and ensure that that jar is on your classpath when you run this.
As a side note, to help you debug things in the future: Exceptions have at least 4 interesting bits of info in them (the type, the message, the trace, and the causal chain). Printing all that is hard, so don't try. Either [A] handle the exception (and printing it or logging it is NOT handling it!) or just throw it onwards. your main method should generally have throws Exception tacked on. It also saves a huge amount of written code (no need for a bunch of try/catch blocks with a crappy 'print the error' code in the catch block!
So, definitely, delete the try, the catch, the print, and add 'throws Exception' to your method instead.

JDBC cannot be resolved to a variable in Eclipse

Currently trying to use a sqlite-dbc4-3.8.2-SNAPSHOT.jar that was given to me as part of an assignment. I've tried running my main file and I get the errors below:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
org.sqlite.JDBC cannot be resolved to a variable
at DbBasic.open(DbBasic.java:54)
at DbBasic.<init>(DbBasic.java:67)
at DbUser.<init>(DbUser.java:40)
at Main.go(Main.java:12)
at Main.main(Main.java:65)
Here's part of the DbBasic class that attempts to connect and open a database using JDBC:
private Connection getConnection()
// get the connection
{
Connection con = null;
try {
con = DriverManager.getConnection(SQLITE_DATABASE_LOCATION+dbName);
con.setAutoCommit(false);
}
catch (SQLException sqle)
{
notify("Db.getConnection database location ["+SQLITE_DATABASE_LOCATION+"] db name["+dbName+"]", sqle);
};
return con;
} // end of method "getConnection"
private void open()
// "open" the database : actually really setting up the connection and obtaining the metadata about the server
// makes sure that database file is present before trying to establish connection
// otherwise SQLite will create a new, empty database with the name provided
{
File dbf = new File(dbName);
if (dbf.exists() == false)
{
System.out.println("SQLite database file ["+dbName+"] does not exist");
System.exit(0);
};
try {
Class.forName(org.sqlite.JDBC);
con = getConnection();
} catch ( ClassNotFoundException cnfe ) {
notify("Db.Open",cnfe);
};
if (debug) System.out.println("Db.Open : leaving");
} // end of constructor "Open"
I have already tried adding external JAR's and the .jar file is then added to my 'Referenced Libraries' in Eclipse.
I'm having trouble understanding the Class.forName(org.sqlite.JDBC) and how to make it work with my .jar file
Though the post is relatively old and the OP might not be interested in a solution for this issue now anymore, thought of putting this as an answer. It might help someone who runs into such silly issues. This is one of the common mistakes that people do while using Eclipse as an IDE, try to run code that doesn't even compile.
You can check the "Problems" view in Eclipse and fix the compilation errors and then try to compile your program. The obvious error here on this question is the missing double quotes "" while using the driver name.
Class.forName("org.sqlite.JDBC");

Error :Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException:

My code is :
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "jdbc:sqlserver://localhost:1433;" +
"databaseName=Java-Test;user=sa;password=199088037635;";
link = (Connection) DriverManager.getConnection(connectionUrl);
} catch (ClassNotFoundException e) {
System.out.println("Class Error: "+ e.toString());
} catch (SQLException se) {
System.out.println("Driver Error: " + se.toString());
}
I get the error :
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: com.microsoft.sqlserver.jdbc.SQLServerConnection cannot be cast to com.sun.corba.se.pept.transport.Connection
at SQL.createAndShowGUI(SQL.java:42)
Similar code in other projects runs correctly. But in this project it doesn't run.
Check your imports. When you type in a class name the IDE checks whether it's something already in scope, and, if not, it gives you suggestions for what you can import. The problem is, the IDE doesn't know which suggestions are more relevant so it can't order them so the most likely one comes up first. Nevertheless, people get used to taking the IDE's first suggestion reflexively, which can result in getting something (with the same name but from a totally different package) that isn't what you want at all.
I'm guessing the IDE inserted a line like
import com.sun.corba.se.pept.transport.Connection;
where it should be
import java.sql.Connection;
which is the JDBC interface that com.microsoft.sqlserver.jdbc.SQLServerConnection implements.
DriverManager.getConnection returns a java.sql.Connection and usually that interface exposes all the funcitonality you need, so you shouldn't need a cast here.
Include this library in the build path of your project.
In Eclipse, this is done by **right clicking on the project > properties > Java Build Path > Add JARs...

Getting oracle.jdbc.driver.LogicalConnection, need oracle.jdbc.OracleConnection

I am trying to connect to an Oracle database inside a Java application running on WebSphere. I need to be able to create an array descriptor to use in a call to a procedure.
The code looks like this:
Connection conn=null;
ArrayDescriptor arrayDescriptor;
Connection tmpCon = jdbcTemplate.getDataSource().getConnection();
conn = WSCallHelper.getNativeConnection(tmpCon);
arrayDescriptor = ArrayDescriptor.createDescriptor("t_my_array",conn);
IDs = new oracle.sql.ARRAY(arrayDescriptor, conn, list.toArray());
The line that calls ArrayDescriptor.createDescriptor throws a class cast exception
java.lang.ClassCastException: oracle.jdbc.driver.LogicalConnection incompatible with oracle.jdbc.OracleConnection
at oracle.sql.ArrayDescriptor.createDescriptor(ArrayDescriptor.java:149)
at oracle.sql.ArrayDescriptor.createDescriptor(ArrayDescriptor.java:115)
Walking through this with the debugger, I can see that conn is definitely a oracle.jdbc.driver.LogicalConnection. The problem is I can't actually reference LogicalConnection in my code because that class is not public, so I can't just do something like this:
arrayDescriptor = ArrayDescriptor.createDescriptor("t_my_array",((LogicalConnection)conn).getWrapper());
.
And this:
arrayDescriptor = ArrayDescriptor.createDescriptor("t_my_array",((oracle.jdbc.driver.OracleConnection)conn).getWrapper());
also returns a class cast exception:
java.lang.ClassCastException: oracle.jdbc.driver.LogicalConnection incompatible with oracle.jdbc.driver.OracleConnection
I need to have an OracleConnection object, but I can't seem to get one from the LogicalConnection that gets returned to me. Has anyone ever seen this before? I feel I'm missing something really obvious here, but maybe I just need another cup of coffee...
#Alex Poole pointed me in the right direction. Maven was including an Oracle jar, version 10.2.0.1.0, and WebSphere had the same jar, but version 10.2.0.4.0.
After fixing the POM so that the 10.2.0.1.0 version jar didn't get deployed, the problem seems to be resolved.

Issues with Class.forName in Java code using Eclipse IDE

I am using Eclipse IDE Version: Helios Service Release 2 and JDK version 1.6. I have SQL Server 2008 installed on my system. I have downloaded Microsoft JDBC driver and included the path of the jar file in Eclipse IDE-> Project Properties->Java build Path-> Libraries -> Add External jars.
I have written this piece of code for database connection:
package com.ucs.test;
import java.sql.*;
public class ConnectDatabase {
Connection DBconnection = null;
String dbName = "silkopenview";
String userName = "SilkTestAdmin";
String password = "Nbv12345";
Class.forName(drivername);
DBconnection = DriverManager.getConnection(dbName,userName,password);
}
But I get the following errors:
Syntax error on token "DBconnection", VariableDeclaratorId expected after this token
Syntax error on token "drivername", VariableDeclaratorId expected after this token
Syntax error on token(s), misplaced construct(s)
I am new to Java and Eclipse IDE. Please help me in correcting this errors. A quick help is appreciated.
These statements:
Class.forName(drivername);
DBconnection = DriverManager.getConnection(dbName,userName,password);
are currently just part of the class - not in a method, or constructor, or static initializer etc. You probably want to put them in a constructor. The previous ones are okay, as they're variable declarations - although whether you really want them to be instance variables is a different matter.
Also note that driverName isn't declared anywhere in the code you've given.
On a tangential note, if you're sufficiently new to Java that you're running into this sort of thing, you should abandon your current code completely: you're currently trying to run before you can walk. Talking to databases correctly is non-trivial, and trying to learn how to do that while also learning Java syntax is going to be messy. Start with simple console apps that let you learn the language and some of the core types (strings, numbers, collections etc) and then move on to databases.
Class.forName(drivername);
DBconnection = DriverManager.getConnection(dbName,userName,password);
You can not put them where you placed in your class, You have to put them in constructor/method, like :
public class ConnectDatabase {
Connection dbConnection = null;
String dbName = "silkopenview";
String userName = "SilkTestAdmin";
String password = "Nbv12345";
public Connection getConnection() {
Class.forName(drivername);
dbConnection = DriverManager.getConnection(dbName,userName,password);
return dbConnection;
}
}
You need to place your statements in a method rather than in the class block.
Class.forName(drivername);
and
DBconnection = DriverManager.getConnection(dbName,userName,password);
Given that you're using SQL Server, you will need to declare your driverName:
final String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";

Categories

Resources