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.
Related
I have the following code
import java.sql.*;
public class UserLogin {
public static void main(String[] args) {
try {
// Load MS accces driver class
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// C:\\databaseFileName.accdb" - location of your database
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\AGENDAS\\Agenda.accdb";
// specify url, username, pasword - make sure these are valid
Connection conn = DriverManager.getConnection(url, "Java2016", "Java2016");
System.out.println("Connection Succesfull");
} catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
}
and it throws the next error
Got an exception!
sun.jdbc.odbc.JdbcOdbcDriver
How can I make the connection?
If you already use JDK8, I suppose the exception you get is a "class not found" exception. But since you did not post the full stack trace, it is not sure - yet, the class name in the output is a strong pointer in that direction.
Please check the source of your initialization of the JDBC URL, I would be interested. In the driver docs, this style is not listed:
9.3.5 What Is the JDBC URL Supported by the Bridge? The Bridge driver uses the odbc subprotocol. URLs for this subprotocol are of the
form:
jdbc:odbc:<data-source-name>[<attribute-name>=<attribute-value>]*
For example:
jdbc:odbc:sybase
jdbc:odbc:mydb;UID=me;PWD=secret
jdbc:odbc:ora123;Cachesize=300
http://download.oracle.com/otn_hosted_doc/jdeveloper/904preview/jdk14doc/docs/guide/jdbc/getstart/bridge.doc.html
Additionally, this is what I found on the state of the ODBC driver.
Status of the JDBC-ODBC Bridge
The JDBC-ODBC Bridge should be considered a transitional solution; it
will be removed in JDK 8.
http://docs.oracle.com/javase/7/docs/technotes/guides/jdbc/bridge.html
Since you are currently starting the project, it seems wise not to use the JDBC-ODBC bridge. Instead use JDK8 and find a solution involving SQL.Server express edition...
Since you are using Access i suggest using UCanAccess which is an open-source Java JDBC driver implementation that allows java developers and jdbc client programs to read/write Microsoft Access database (.mdb and .accdb files).
I think it's simpler and has more support than the traditional JDBC-ODBC bridge.
After downloading the UCanAccess driver, this is how you can set up your connection :
private Connection con ;
private Statement stmt;
public void connect ( String path ){
try {
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
this.con = DriverManager.getConnection(path, "", "");
this.stmt = con.createStatement();
} catch (SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
catch (ClassNotFoundException e) {
System.err.println("classnotfoundException: " + e.getMessage());
}
}
I'm working on a program for fun but the MySQL driver and connection code isn't working properly I got the error
Error: no suitable driver found
MeanWhile my code contains the Class.forName("com.mysql.jdbc.Driver"); line. I have the newest MySQL jar file in my class path. any suggestions I could try to fix the problem
private void connect() {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(URL,user,pass);
stmt = con.createStatement();
} catch (Exception e) {
error = true;
e.printStackTrace();
}
}
Your issue is in the syntax of the URL which is not correct you forgot the colon after mysql, it should be jdbc:mysql://... for more details about the syntax of the URL in case of mysql please refer to this web page
I load JDBC SQL Server drivers to connect to a database after the whole process I want to unload all the registered drivers
To register the drivers I use
static {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Class.forName("net.sourceforge.jtds.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
How can I deregister all these drivers?
I tried the following but it seems not to be working
Enumeration<Driver> drivers = DriverManager.getDrivers();
while(drivers.nextElement() != null){
Driver d = drivers.nextElement();
try {
DriverManager.deregisterDriver(d);
} catch (SQLException e) {
e.printStackTrace();
}
}
I get the following exception
java.util.NoSuchElementException: Vector Enumeration
Edit
Now I get the following error when I run another task which also needs a connection to database using JDBC
WARNING: Failed to load the sqljdbc_auth.dll cause : Native Library C:\sqljdbc_4.0\enu\auth\x86\sqljdbc_auth.dll already loaded in another classloader
any idea?
You have to ensure there's an element with hasMoreElements() before using it with nextElement().
See also the javadoc: https://docs.oracle.com/javase/8/docs/api/java/util/Enumeration.html
While the build paths are not correct I obtain “com.microsoft.sqlserver.jdbc.SQLServerDriver” from the stack trace. As they are built correctly, I obtain my printed statement “Successfully connected”. The JDBC is living within the getter/setters of the webservice as a method.
When I place the JDBC content in its own file with no builds and run as a java application I receive: “com.microsoft.sqlserver.jdbc.SQLServerDriver”
When I place the JDBC content in its own file with builds and run as a java application I receive: “Successfully connected”
When the method is called from a test file as a java application I receive: “Successfully connected”
Ex:
public static void main(String[] args) {
insert.main(args);
When the method is run as a java application on PO I receive: “Successfully connected”
When I place the method to be called under a setter (which will be invoked by the client, which will cause the jdbc to be invoked) I receive: “com.microsoft.sqlserver.jdbc.SQLServerDriver”
Would you happen to have any tips for me? I’m clueless why it will work under being invoked as an application but not via client?
public class insert{
public static void main(String[] args) {
Connection con = null;
Statement st = null;
final String DB_URL = "jdbc:jtds:sqlserver://00.00.00.00:0000/DB";
// Database credentials
final String USER = "usrname";
final String PASS = "pw";
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(DB_URL, USER, PASS);
st = con.createStatement();
System.out.println("successfully connected!");
} catch (Exception err) {
System.out.println(" " + err.getMessage ());
}
finally {
try {
con.close();
} catch (Exception e) { /* ignored */ }
try {
st.close();
} catch (Exception e) {
/* ignored */
}
}
}
}
Any tips at this point would be greatly appreciated.
The problem is that your jar misses the necessary libraries that provides com.microsoft.sqlserver.jdbc.SQLServerDriver class and others to communicate with your SQL server. You have to make sure the library is loaded and available when is being executed from tomcat. Just copy your library and drop it inside %TOMCAT_INSTALL%/lib folder, where %TOMCAT_INSTALL% is the folder where your tomcat is installed, so the library will be available for every project (war, jar, etc) that runs in your tomcat installation.
I've set the classpath envoirenment but still get an error "Exception:com.mysql.jdbc.Driver"
Do you have any idea what might be wrong?
Here is my test code:
import java.sql.*;
public class JdbcExample1 {
public static void main(String args[]) {
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql:///test", "root", "secret");
if(!con.isClosed())
System.out.println("Successfully connected to MySQL server...");
} catch(Exception e) {
System.err.println("Exception: " + e.getMessage());
} finally {
try {
if(con != null)
con.close();
} catch(SQLException e) {}
}
}
}
Exception:com.mysql.jdbc.Driver
Is most probably not the full error message. I guess it's a ClassNotFoundException and you simply do not have the MySQL JDBC driver as part of your classpath.
When running your program, you need to list the driver as well
java -cp .;mysql-connector-java-5.1.7-bin.jar JdbcExample1
(This assumes JdbcExample1.class and the .jar file are in the current directory)
I've set the classpath envoirenment
Setting the CLASSPATH environment variable is not necessary anymore (actually it never has been necessary). As a matter of fact it creates more problems than it solves.
Use the above syntax to supply the path to your driver and run your program
As horse says, I'm pretty sure it's a 'ClassNotFoundException'.
To be sure add "e.printStackTrace();" in your catch-block.
Always best to get a stack trace.