问题
I use the programs: eclipse and mysql.
I have a database in mysql and I want to connect between the eclipse to the mysql.
I have some folders in my project that I created in the eclipse.
I have the main folder: testest.. and I show you what I have in the relevant folders:
testest
..src
....testest
......testestservlet.java
..app engine sdk
..JRE system library
..referenced library
..war
..lib
....mysql-connector-java-5.1.22
I updated my testestservlet.java:
package testest;
import java.io.IOException;
import javax.servlet.http.*;
import java.sql.*;
@SuppressWarnings("serial")
public class TestestServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/plain");
resp.getWriter().println("Hey, world");
resp.getWriter().println("MySQL Connect Example.");
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "database_alon";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "ADMINALON";
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
resp.getWriter().println("Connected to the database");
conn.close();
resp.getWriter().println("Disconnected from database");
} catch (Exception e) {
e.printStackTrace();
}
}
}
now, I run testest by run as->web application.
enter the url: localhost:8888
and only see the 'hello world'.
I read about that and see that I need to write the command:
set CLASSPATH=%CLASSPATH%;JAVA_HOME\lib;
but what are the url-s of my CLASSPATH and JAVA_HOME should be? I have folders of: c:/program_fils/java and: c:/Jconnector (something like that).
the folder of Jconnector contains a file of: mysql-connector-java-5.1.22.jar
I tried to add the JAR into the libraries via the eclipse (right click on testest->properties->Libraries->add external jar->mysql-connector-java-5.1.22-bin.jar:
p.s, my operating system is windows 32bit.
回答1:
There is no need of doing
set CLASSPATH=%CLASSPATH%;JAVA_HOME\lib;
Just add mysql-connector-java-5.1.22-bin.jar: to /WEB-INF/lib directory.
Eclipse is smart enough to recognize .jar files added under /WEB-INF/lib and should include in the CLASSPATH.
Adding a library using "Add External Jar" should also work but its not best practice.
Dropping ".jar" inside /WEB-INF/lib will also work when you externally deploy your web apllication using .war
回答2:
Adding the mysql-connector-java-5.1.22-bin.jar to WE-INF\LIB should resolve this issue. Adding jar file via
properties -> build path -> add external jar
is not a sure shot siolution as various platforms of Eclipse behave differently. However adding the above mentioned jar file should surely make the JDBC program work.
来源:https://stackoverflow.com/questions/13442747/set-the-classpath-in-order-to-connect-between-mysql-to-jdbc