How to import JDBC driver into Dynamic Web Project?

后端 未结 3 2136
孤街浪徒
孤街浪徒 2020-12-20 04:16

I have a local MySQL database. When I created a simple Java project, with one class which contained only main, I successfully retrieved some data from the database using JDB

相关标签:
3条回答
  • 2020-12-20 04:43

    There are two ways to use and reference a jar file in an eclipse project.

    • One is at compile time and for compilation purposes. To make your project compile, you need to add your required libraries in the classpath. In eclipse, right click to your project, hover on 'Build Path', then select 'Configure Build Path'. In the dialog go to 'Libraries' tab and there you can see which jars/libraries you have. If you need to add more, you can use the buttons at the right side of the dialog. There you should select 'Add external jars' and select the MySql JDBC Driver from your file system.

    • The other one is at run time. This is when you deploy your web application to an application server. Now everytime your application needs to load a class from an external jar, it will look for the jar in the application server's class loader. The classloader conatins the paths to the available jar files in your application server, in configured resources and in your deployed application in the WEB-INF/lib/ folder. You can configure which place the classloader will check first.

    In your very specific case, you need to add the MySQL JDBC Driver in any of classloader paths (since I asume your project compiles already) so you can either add the jar to Tomcat's /lib directory or to your application's /WEB-INF/lib/ directory. After that just redeploy or restart tomcat and you should be able to use MySQL JDBC connections.

    UPDATE:

    Also, when using a DriverManager interface to create a JDBC Connection, remember to always create an instance of your JDBC driver first in order to load it into your Classloader. You can see this in the MySQL JDBC Driver documentation. Ej:

    Class.forName("com.mysql.jdbc.Driver").newInstance();

    Call this line before using DriverManager.getConnection(...) and you should now be able to create and use your JDBC Connections.

    0 讨论(0)
  • 2020-12-20 04:46

    Your mysql jdbc driver should be placed into your tomcat's directory:

    catalina_base/webapps/app_name/WEB-INF/lib/

    Make sure to start/restart your server after placing your new mysql jdbc driver jar file there.

    0 讨论(0)
  • 2020-12-20 04:56

    just place your driver jar file into WEB-INF/lib folder.

    0 讨论(0)
提交回复
热议问题