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.
Related
I have SQL Express 2012 installed on my local machine. I tried connecing with it, by using JDBC 6.2. I downloaded it and declared the dependency(IntelliJ: CTRL, SHIFT, ALT + S --> "Modules" --> "Add" --> "Jars or directories").
Eventually I adjusted the provided code above to my needs, looking like the following:
For some reason, the imported class is not being used at all(it´s greyed out by IntelliJ) - did I made a mistake in terms of dependencies? I´m fairly new to JAVA: to my understanding, setting up the classpath is equal to setting up the depndencies(?).
Moreover I get the error "connection refused". I checked different login credentials as well as the ports(SQL configuration manager as well as netstate) - they are fine. Both, Windows- and SQL authentication didn´t work.
What am I missing?
package com.company;
import java.sql.*;
import com.microsoft.sqlserver.jdbc.*;
public class Main {
public static void main(String[] args) {
String connectionString = "jdbc:sqlserver://localhost:1433;"
+"database=QMT;"
+"user=superadmin;"
+"password=myPassword.;";
// Declare the JDBC objects.
Connection connection = null;
try {
connection = DriverManager.getConnection(connectionString);
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (connection != null) try { connection.close(); } catch(Exception e) {}
}
}
}
I'm trying to connect my DB with a Java Application i'm creating. What I got so far:
public class DBConnect {
public void DBConnect() {
try {
DBConnect DBConnect = null;
String url = "jdbc:mysql://localhost:3306/ähs_system";
String uName = "**";
String uPass = "**";
// Connection conn = DriverManager.getConnection(url, uName, uPass);
System.out.println("DB Connected");
}
catch (Exception Err) {
System.out.println("Error while connecting: " + Err.getMessage());
System.exit(0);
}
}
}
It's a runnable code although i'm still able to run the code without any error messages if I change my uName and/or Upass. So based on that information i'm gonna say that it's not actually connecting to the database at all...
Anyone with a few tips or tricks I can use?
I've loaded the DB in services and I am able to reach it and add data and run other SQL commands within netbeans but that's basically it. I've also loaded the mysql-connector-java-5.1.35 driver.
Run Code:
public static void main(String args[]) {
try {
DBConnect DBConnect = new DBConnect ();
DBConnect.DBConnect();
}
catch (Exception e){
System.out.println("Cannot connect to DB. Error: " + e.getMessage());
}
Let me know if you need any furthur information!
Updating property file: C:\Users\Johan\Documents\NetBeansProjects\KiltenRos\build\built-jar.properties
Compiling 1 source file to C:\Users\Johan\Documents\NetBeansProjects\KiltenRos\build\classes
C:\Users\Johan\Documents\NetBeansProjects\KiltenRos\src\kiltenros\DBConnect.java:23: error: incompatible types: java.sql.Connection cannot be converted to kiltenros.Connection
Connection conn = DriverManager.getConnection(url, uName, uPass);
1 error
C:\Users\Johan\Documents\NetBeansProjects\KiltenRos\nbproject\build-impl.xml:923: The following error occurred while executing this line:
C:\Users\Johan\Documents\NetBeansProjects\KiltenRos\nbproject\build-impl.xml:263: Compile failed; see the compiler error output for details.
BUILD FAILED (total time: 0 seconds)
the error log is clear
java.sql.Connection cannot be converted to kiltenros.Connection
it seems that you imported the wrong class in the beginning of your class
DriverManager.getConnection(url, uName, uPass) return you instance of java.sql.Connection.
btw, change your local variable DBConnect to dbConnect so it won't has the same name as your class DBConnect and it will follow the java convention (lowercase on 1st letter of a variable)
I've very little experience with MySQL, but I avoid using "ä" in a database name. Perhaps, the underscore isn't allowed.
As per your stacktrace it seems you have not imported the correct Connection class. Delete the Connection file in your project and import java.sql.Connection.
The problem seemed to be a corrupted rs2xml.jar file. Once I reloaded it and it worked.
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.
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 trying to do a JNDI lookup on a data source that lives in Weblogic 10.3.5.
I have the following code:
try {
//jbInit();
env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory");
env.put(javax.naming.Context.PROVIDER_URL,"t3://localhost:7001");
try {
Context ctx = new InitialContext(env);
javax.sql.DataSource ds = (javax.sql.DataSource) ctx.lookup("jdbc/sandboxDS");
conn = ds.getConnection();
} catch(Exception e){
e.printStackTrace();
}
if(conn != null){
System.out.println("Got connection...");
String colDescQuery =
"select column1 from my_table where table_name = 'your_table' order by col_order_no";
Statement colDescStmt = conn.createStatement();
ResultSet colDescRS = colDescStmt.executeQuery(colDescQuery);
while (colDescRS.next()) {
System.out.println(colDescRS.getString(1));
}
} else {
System.out.println("No connection...");
}
} catch (Exception e) {
e.printStackTrace();
}
When I run this code as a stand alone Java program it works perfectly. The connection is found and the query returns the expected results.
When I use the same code in an applet and run it from the JDeveloper applet viewer it hangs where the InitialContext is instantiated. No exceptions are thrown, it simply hangs never to return.
Any ideas as to what is going on here? I have weblogic.jar and wlthint3client.jar in my classpath for both runs.
Thanks...
Applets have sandbox restrictions, so they cannot connect to the server other than where they were downloaded from.
Make sure your applet is also deployed to the same WebLogic Server that your JNDI data source is on.