JDBC Driver won't load - java

I already saw many post where people were trying to add the driver. I'm using intelij as IDE and added the driver under Modules => Dependencies => Add Jar; So my IDE identified the driver and can show me the source file of it. My problem is, as soon i start my server I'll get that error that he couldn't find the driver:
My Code:
private void createDB()
{
try {
Class.forName("com.mysql.jdbc.Driver");
database = DriverManager.getConnection("jdbc:mysql://***:" + 3307 + "/**db", "", "");
} catch (Exception e) {
e.printStackTrace();
}
}
My exception:
> java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader.findClass(Unknown Source)

Related

Jar file not connecting to existing database

I have a JAR file that doesn't connect to the database even though it connects just fine in the IDE. I'm stuck and I don't know where to go from here. I am using Java 8 in IntelliJ trying to run SQLite.
Here is the code for the Database class.
private static Connection connection = null;
private static boolean connected = false;
static void connect() {
String driver = "org.sqlite.JDBC";
String db = "schedulerDB";
String path = "lib\\";
String url = "jdbc:sqlite:";
try {
Class.forName(driver);
connection = DriverManager.getConnection(url + path + db);
printInfo("Connected to database : " + db);
connected = true;
} catch (SQLException e) {
printError(1100, "Could not connect to database", e);
} catch (ClassNotFoundException e) {
printError(1101, "Driver not found error", e);
}
}
When I run the JAR file in the terminal, I get:
org.sqlite.SQLiteException: [SQLITE_ERROR] SQL error or missing database (no such table: user)
Please help me.
Added e.printStackTrace(); as requested:
org.sqlite.SQLiteException: [SQLITE_ERROR] SQL error or missing database (no such table: user)
at org.sqlite.core.DB.newSQLException(DB.java:941)
at org.sqlite.core.DB.newSQLException(DB.java:953)
at org.sqlite.core.DB.throwex(DB.java:918)
at org.sqlite.core.NativeDB.prepare_utf8(Native Method)
at org.sqlite.core.NativeDB.prepare(NativeDB.java:134)
at org.sqlite.core.DB.prepare(DB.java:257)
at org.sqlite.jdbc3.JDBC3Statement.execute(JDBC3Statement.java:52)
at scheduler.Database.query(Database.java:337)
at scheduler.User.buildList(User.java:42)
at scheduler.User.<clinit>(User.java:85)
at scheduler.Main.start(Main.java:27)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$8(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$7(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$5(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$6(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$4(WinApplication.java:186)
at java.lang.Thread.run(Unknown Source)
Change the value of url to
url = "jdbc:sqlite::resource:"
Your exception is actually caused by a MalformedURLException. The reason you are getting this is because lib\schedulerDB is not a valid URL.
URLs must use forward slashes (/), on all systems—even Windows. This is a requirement of the URI specification itself. (A URL is a type of URI, so every URL must conform to the rules of a URI.)
Making your URL valid should do the trick:
String path = "lib/";

DeviceDriver connection statement not executing

I'm new to setting up connections to mysql servers, I have already defined a database, and set up tables within it, but I am having issues with connecting to it.
It seems that it is not executing the statement at all, and is throwing an error every time I try it.
import java.sql.*;
public class initDB {
public static void main(String[] args) throws Exception{
Connection dbcon = null;
try {
System.out.println("tried try statement");
Class.forName("com.mysql.jdbc.Driver");
System.out.println("tried driver");
dbcon = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/raindatabase", "user", "loginsystem"
);
System.out.println("tried to get connection");
} catch (Exception e){
e.printStackTrace();
}
}
}
It throws this error message:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:190)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:499)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Class.java:291)
at initDB.main(initDB.java:10)
MySQL connector JAR should be in your class path.
This tutorial will help to understand JDBC connections https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-usagenotes-connect-drivermanager.html
You can download connector from here https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-installing.html
In IntelliJ, you can add jar to library. File -> Project Structure -> Libraries -> {Add your jar}
or, To compile/run from command:
Compile:
javac -classpath PATH_TO_MYSQL_CONNRECTOR_JAR;%CLASSPATH% YOUR_JAVA_FILE.java
Run
java -classpath PATH_TO_MYSQL_CONNRECTOR_JAR;%CLASSPATH% YOUR_JAVA_CLASS_FILE_NAME

When working with tomcat, how are JDBC Drivers loaded?

I am using Eclipse and tomcat 7. I have little experience with either product and for that matter Java itself. I was trying to connect to a derby database from a Servlet. Initially, all I had in my doGet() is the following:
conn = DriverManager.getConnection(connectionURL);
I have connectionURL defined as
static private String connectionURL = "jdbc:derby://localhost:1527/seconddb";
Then I added the following to the Build Path and Deployment Assembly.
C:\DERBY\db-derby-10.10.1.1-bin\lib\derbyclient.jar
That is all I did. I sort of assumed that Tomcat will find the driver class and load it. I got the following error
java.sql.SQLException: No suitable driver found for jdbc:derby://localhost:1527/seconddb
Then I went on to add the following code in doGet() to load the driver class:
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
Now it worked. I thought that after Java 1.4 there was no need to explicitly load JDBC driver class. So what am I doing wrong here? I have given the entire code below.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Connection conn = null;
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
try {
conn = DriverManager.getConnection(connectionURL);
//DriverManager.getConnection("jdbc:derby://localhost:1527/testdb;create=true");
}
catch (SQLException e) {
e.printStackTrace();
}
PrintWriter p = response.getWriter ();
p.println("Connected to database");
try {
if (conn != null) {
conn.close();
}
}
catch (SQLException e) {
e.printStackTrace();
}
}
I am using java 1.7
I cannot really explain why, but here is how I do :
if the driver is located in the war, I must call Class.forName("...Driver"); in in initialization method somewhere in the web application.
if the driver is located in Tomcat libraries, it is automacally loaded when I need it.
I know it's more a rule of thumb than a clear explaination, but my knowledge in class loading does not allow me to a better answer ...
Your Derby driver doesn't support the JDBC 4 auto-loading, so you have to do it manually. Try to find a more up to date version.
I could be wrong here but in your second code sample connectionURL
static private String connectionURL = "jdbc:derby://localhost:1527/seconddb";
doesn't include "create=true"; to complete the statement. In your full code sample it's included, but commented out.

No suitable driver found for jdbc:sqlserver://repcode;DatabaseName=reporting

I have Eclipse Kepler and added sqljdbc4.jar to the classpath using properties on the project and then 'Java Build Path" and finally added under Libraries.
When I tries running the code (Run on server) i get the error:
java.sql.SQLException: No suitable driver found for jdbc:sqlserver://repcode;DatabaseName=reporting
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
The code:
package com.example.viewreport;
import javax.servlet.annotation.WebServlet;
import java.sql.*;
#SuppressWarnings("serial")
#Theme("viewreport")
public class ViewreportUI extends UI {
.......... CUT ..................
String userName = "report";
String password = "report";
String url = "jdbc:sqlserver://repcode;DatabaseName=reporting";
try {
Connection conn = DriverManager.getConnection(url, userName, password);
} catch (SQLException e) { // TODO Auto-generated catch block
e.printStackTrace();
}
}
Some vaadin code is stripped out from the above source.
What am I missing?
The SQL server is a 2008 R2
The code is run on a local tomcat catalina instance
Try This
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
Connection connection=DriverManager.getConnection("jdbc:microsoft:sqlserver://localhost/DatabaseName","userName","password");
Try adding this line before creating a connection. Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

Java not connecting to MS Access database using Eclipse

Can anyone help me? I've already tried to solve this for one hour and I'm still confused.
Below is my code and i get this error when compiling.
Output msg::
DriverLoaded
Could Not Connect to Databasejava.sql.SQLException: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
at sun.jdbc.odbc.JdbcOdbc.createSQLException(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.standardError(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.SQLDriverConnect(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcConnection.initialize(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at DBConnect.<init>(DBConnect.java:11)
at DBConnect.main(DBConnect.java:21)
Code::
import java.sql.*;
public class DBConnect {
public DBConnect() {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("DriverLoaded");
String url = "jdbc:odbc:; DRIVER = Microsoft Access Driver (*.mdb, *.accdb); DBQ = DB.accdb";
Connection con = DriverManager.getConnection(url);
System.out.println("Connection Established Successfully");
} catch(Exception e) {
e.printStackTrace();
System.out.println("Could Not Connect to Database");
}
}
public static void main (String args[]) {
DBConnect dbcon = new DBConnect();
}
}
Overloaded methods for getConnection()
1)
getConnection( String url, Properties info )
url -
a database url of the form jdbc:subprotocol:subname
info -
a list of arbitrary string tag/value pairs as connection arguments;
normally at least a "user" and "password" property should be included
2)
getConnection( String url, String user, String password )
url - a database url of the form jdbc:subprotocol:subname
user -
the database user on whose behalf the Connection is being made
password -
the user's password
3) getConnection( String url )
url -
a database url of the form jdbc:subprotocol:subname
Considering you're using the last constructor, it seems your url syntax in incorrect. I'm not familiar with MS Access, but I'll offer a suggestion I found on another answer.
This is your syntax
"jdbc:odbc:; DRIVER = Microsoft Access Driver (*.mdb, *.accdb); DBQ = DB.accdb"
A correct syntax I found was
File f = new File("\\\\***\\***\\****\\***.accdb");
"jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + f.getAbsolutePath();
Looks like you have an unnecessary semicolon after odbc and an extra space. Maybe you want to try the above syntax and see what happens. I'm not sure about the file part, but you may want to look into it if your url still fails after making the semicolon/space fix.
Check out this question also for more info on another option Connection with username and password
below is the working code for your problem...
import java.sql.*;
public class DBConnect {
public DBConnect() {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("DriverLoaded");
String url = "jdbc:odbc:instance";
Connection con = DriverManager.getConnection(url);
System.out.println("Connection Established Successfully");
} catch(Exception e) {
e.printStackTrace();
System.out.println("Could Not Connect to Database");
}
}
public static void main (String args[]) {
DBConnect dbcon = new DBConnect();
}
}
steps to be followed:
create an access database DB.accdb in any directory of your windows xp system.
open start > controlpanel > Performance and maintanance > Administrative Tools > Data sources (ODBC) >click System DSN tab > click add > choose Microsoft Access Driver (accdb,mdb) > give the name : instance , (since, getConnection("jdbc:odbc:instance") and click and browse the DB.accdb located in your hard drive ) press ok and restart your command prompt. and run the code again.
Running the same code in eclipse
create a java project.
add a main class and edit the source of this main class. just copy and paste the about code.
create a user library by adding the jar files from the jdk/bin directory.
link the build path to the project by linking the userlibrary.
run the project.

Categories