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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19412135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 16:56:25  来源:igfitidea点击:

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

javamysqlservletsjdbc

提问by Lego_blocks

I am having this error on Netbeans 7.2, it says that ClassNotFoundexception and InstantationException. I am really stuck on this matter. Kindly help me.

我在 Netbeans 7.2 上遇到了这个错误,它说 ClassNotFoundexception 和 InstantationException。我真的被这个问题困住了。请帮助我。

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        String driver = "com.mysql.jdbc.Driver";
        con = null;
        String username = "";
        String password = "";

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

        con = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbName", "root", "password");
        Statement st = con.createStatement();
        ResultSet mar = st.executeQuery("SELECT * FROM table");


        Gson gson = new GsonBuilder().create();
        response.setContentType("application/json");  
        response.setCharacterEncoding("utf-8"); 

    } catch (SQLException e) {
                String message = e.getMessage();
    }

采纳答案by ScalaWilliam

What about this simple way?!

这个简单的方法呢?!

java.sql.Driver d=new com.mysql.jdbc.Driver();

I also wondered why do you connect to database with such this way?! It's better let server manage it.

我也想知道你为什么用这种方式连接到数据库?!最好让服务器管理它。

First config the context.xml(if you are using tomcat) like this:

首先context.xml像这样配置(如果您使用的是tomcat):

<context>
<Resource name="_ds" auth="Container" type="javax.sql.DataSource"
               maxActive="128" maxIdle="32" username="_admin" password="qwerty" driverClassName="com.mysql.jdbc.Driver"
               url="jdbc:mysql://127.0.0.1:3306/dbname"/>
</context>

Then, simple get a connection from this resource in servlet/etc, like this:

然后,简单地从 servlet/etc 中的该资源获取连接,如下所示:

public void init() {
    try {
        _ds = (DataSource) InitialContext.lookup("java:/comp/env/_ds");
    } catch (Exception ex) {
    }
}

private javax.sql.DataSource _ds;

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
{
    try {
        /*String driver = "com.mysql.jdbc.Driver";
        con = null;
        String username = "";
        String password = "";

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

        con = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbName", "root", "password");*/
        Connection con=_ds.getConnection();
        Statement st = con.createStatement();
        ResultSet mar = st.executeQuery("SELECT * FROM table");


        Gson gson = new GsonBuilder().create();
        response.setContentType("application/json");  
        response.setCharacterEncoding("utf-8"); 
        con.close();
    } catch (SQLException e) {
        String message = e.getMessage();
    }

By the way, don't forget to compy the MySQL JDBC driver jar-file in <CATALINA_BASE>/libfolder.

顺便说一句,不要忘记在<CATALINA_BASE>/lib文件夹中编译 MySQL JDBC 驱动程序 jar文件。

回答by Aniket Thakur

All you need is Class.forName("com.mysql.jdbc.Driver")

所有你需要的是 Class.forName("com.mysql.jdbc.Driver")

This acts like class loader and load your driver class for you. For that you need to add the corresponding jar file(which has the driver implementation). So download and add mysql-connector.jarin your class path.

这就像类加载器并为您加载驱动程序类。为此,您需要添加相应的 jar 文件(具有驱动程序实现)。所以下载并添加mysql-connector.jar到你的类路径中。

Note : If you are using Java 7 then there is no need to even add the Class.forName("com.mysql.jdbc.Driver")statement.Automatic Resource Management (ARM) is added in JDBC 4.1 which comes by default in Java 7.

注意:如果您使用的是 Java 7,则甚至不需要添加该Class.forName("com.mysql.jdbc.Driver")语句。自动资源管理 (ARM) 在 Java 7 中默认提供的 JDBC 4.1 中添加。

回答by ScalaWilliam

You might want to solve a bigger problem. You ought not enter configuration data such as database connection information directly in your servlet.

你可能想解决一个更大的问题。您不应直接在 servlet 中输入配置数据,例如数据库连接信息。

Are you using Tomcat? You can simply use JNDI. You will be able to change database details and drivers without having to recompile your servlet.

你用的是Tomcat吗?您可以简单地使用 JNDI。您将能够更改数据库详细信息和驱动程序,而无需重新编译您的 servlet。

Here is the Tomcat 7.0 JNDI Datasource HOW-TOshows various ways in which you can get a Connectionto your database.

下面是Tomcat 7.0 JNDI 数据源 HOW-TO,它展示了获取Connection数据库的各种方法。

On that page, you have a code example of how to get a Connection(Oracle 8i, 9i & 10g -> Part 3), and how to write a MySQL specific configuration.

在该页面上,您有一个代码示例,说明如何获取Connection(Oracle 8i、9i 和 10g -> 第 3 部分)以及如何编写 MySQL 特定配置

Make sure to download a correct MySQL jar and place it in your Tomcat's lib/directory (or alternatively your WAR's WEB-INF/lib).

确保下载正确的 MySQL jar 并将其放置在 Tomcat 的lib/目录(或 WAR 的WEB-INF/lib)中。

回答by Pushpendra

You need to add mysqlconnector.jarfile found here: ( http://dev.mysql.com/downloads/connector/j/) into your lib folder of your project. Include it with your project and then you can access your connection with database.

您需要将mysqlconnector.jar在此处找到的文件:(http://dev.mysql.com/downloads/connector/j/)添加到项目的 lib 文件夹中。将它包含在您的项目中,然后您就可以访问与数据库的连接。

Add that jar into the buildpath.

将该 jar 添加到构建路径中。