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...
Related
I need to connect to my database but I keep getting an error that says "driver not found".
I have added mariadb-java-client-3.0.8.jar jar file and it is still not working.
And this works pretty well on NetBeans, but I need to know how to fix that in VScode IDE. Do you know what I am missing?
import java.sql.Connection;
import java.sql.DriverManager;
public class App {
public static void main(String[] args) throws Exception {
try {
Connection conn = DriverManager.getConnection("jdbc:mariadb://localhost:3306/cpit305-project", "root", "");
System.out.println("working");
} catch (Exception e) {
System.err.println(e);
}
}
}
The exception:
java.sql.SQLException: No suitable driver found for jdbc:mariadb://localhost:3306/cpit305-project
First make sure your connection string is correct. Then the database name avoids the use of dashes (-).
The same code works fine for me.
Download the connection package here.
I have faced the same problem. I solved it by exporting classpath into my .zshrc file.
Add this to you shell:
export CLASSPATH=/path/mysql-connector-java-ver.jar:$CLASSPATH
Language: Java
Program: Connecting to a database
Question: I'm trying to connect the sqlite database by following TutorialsPoint tutorial but I keep getting the main class not found error.
Implementation: My code is below followed by my terminal commands and folder structure screenshot. But basically all my files are located in one folder including the sqlite jar file.
import java.sql.*;
public class Test {
public static void main(String[] args) {
Connection c = null;
try{
Class.forName("com.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
} catch(Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
System.out.println("Opened database successfully!");
}
}
Terminal Commands
javac Test.java
java -classpath ".;sqlite-jdbc-3.23.1.jar" Test
Your problem was that you're explicitly trying to load the class com.sqlite.JDBC, whereas the driver class name must've changed somewhere along the way.
JDBC Type 4 drivers have added cleverness which allows you to specify only the connection URL, and the driver loads itself based on the beginning (i.e. jdbc:sqlite). No need to wonder what was the driver class's name.
Rant unrelated to the issue at hand:
Unfortunately people read old tutorials written by less than experts, so we constantly see Class.forName() being used, as well as the more serious issue, which is using Statement instead of PreparedStatement.
My classpath option was incorrect. I was on linux and was trying to do:
java -classpath ".;sqlite-jdbc-3.23.1.jar" Test
the correct way was
java -classpath ".:sqlite-jdbc-3.23.1.jar" Test
colon not semicolon. Unfortunately now it's giving me and error" ClassNotFoundException: com.sqlite.JDBC;
I will look into this.
Thanks for the comments which helped me find the error
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.
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");
I need your help around JAVA RMI, i developped a sample program used to sort table. but i got this exception:
Erreur RemoteException occurred in server thread; nested exception is:
java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
java.lang.ClassNotFoundException: ServicesTableau
and this is my Server source code :
public class Serveur {
public static void main(String args[]) {
try {
System.out.println("Server start ...");
ServicesTableauImpl od = new ServicesTableauImpl();
String url = "rmi://" + args[0] + "/ServicesTableauImpl";
System.out.println("Passe");
Naming.rebind(url, od);
System.out.println("Attente d'invocations de client / CTRL-C pour stopper");
} catch (Exception e) {
System.out.println("Erreur " + e.getMessage());
}
/*
catch(java.net.MalformatedURLException e){
System.out.println("Mauvais nom de serveur");
System.exit(1);
}
catch(RemoteException e){
System.out.println("Pas de Rmiregistry");
System.exit(1);
}
*/
}
}
That class isn't available on the CLASSPATH of the RMI Registry. The simplest way to fix it is to start the Registry in the same JVM, via LocateRegistry.createRegistry(). Store the result in a static field.
This happened to me because I didn't run rmiregistry in the same directory as the server.
I spent a few hours to successfully start the simple example form Orcale!
Hope could help you
First, I run the program on Windows
I totally copy the code from here
but i delete the package and put that three .class file together for the convince
and if you are not familar with this i hope you'd better do it, too
because when package get in, the problem will be more complicated
There are three steps to do:
1.start rmiregistry
start rmiregistry -J-Djava.class.path=./
it is for "remote interface definition"
so that the rmiregistry can find the class
then solve the ClassNotFoundException
2.run server
start java Server
then you can see the output:
Server ready
3.run client
java Client
output:
response: Hello, world!
then talk about how to deal with package
Usually the Server.class and interface.class---"remote interface definition"
should be in the same package
and you need to know how to run the .class with package
java {packagename}.Server
the classpath default is "./"
and package declare will help to locate the interface.class which is needed for Server.class
so we don't need to separately set -cp
BTW, if you try set the real classpath, you will get error instead
As for "start rmiregistry"
it has no default classpath
so we need to set it
and it should be the same as the classpath's default value "./"
In some cases, you need to move you rmi clients code (interface and main) to default package. Repeate it for server side. It can solve you problem(work with packaging in rmi is not so obvious).
The answer is for IDE based project.
you need to 'start rmiregistry' from with in the build folder.
for example:
in Intellij
open terminal inside 'target -> classes' folder
run 'start rmiregistry'
then run your server code using intellij
for eclipse I hope its build folder
This error is because of not writing security manager code, because of which the class can't get loaded.
So make sure you add code for the security manager.
If the compiler doesn't find the security manager then create a new one.Add the code in main method.
if (System.getSecurityManager() == null) then
System.setSecurityManager(new RMISecurityManager())