为什么java不能看到我的mysql驱动

时间:2011-12-04 18:56:10

标签: java mysql sql classpath

我无法解决为什么java无法看到我的mysql驱动程序:

  • 我从mysql网站
  • 下载了驱动程序.jar
  • 我已将jar添加到我的运行时类路径
  • 我可以通过打印出相关的系统属性
  • 来确认jar在类路径上

但我仍然得到ClassNotFound Exceptions。还有什么我需要做的吗?

类示例:

package org.rcz.dbtest;

import java.sql.*;

public class DB {

    private Connection connect = null;
    private Statement stmt = null;
    private PreparedStatement prepared = null;
    private ResultSet rset = null;
    private String driverClassName = "com.myqsl.jdbc.Driver";
    private String jdbcUrl = "jdbc:mysql://localhost/ctic_local?user=root&password=server";
    private String queryString;

    public DB(String query)
    {
        System.out.println(System.getProperty("java.class.path"));
        queryString = query;
    }

    public void readFromDatabase()
    {
        try
        {
            Class.forName(driverClassName);
            connect = DriverManager.getConnection(jdbcUrl);
            stmt = connect.createStatement();
            rset = stmt.executeQuery(queryString);
            writeResultSet(rset);
        }
        catch (ClassNotFoundException cex)
        {
            System.out.println("Could not find mysql class");
        }
        catch(SQLException sqex)
        {

        }
    }

    private void writeResultSet(ResultSet resultSet) throws SQLException {
        // ResultSet is initially before the first data set
        while (resultSet.next()) {
            // It is possible to get the columns via name
            // also possible to get the columns via the column number
            // which starts at 1
            // e.g. resultSet.getSTring(2);
            String user = resultSet.getString("name");
            String comment = resultSet.getString("comment");
            System.out.println("User: " + user);
            System.out.println("Comment: " + comment);
        }
    }



}

我的主要类只是将查询传递到DB类:

package org.rcz.dbtest;

import java.io.IOException;

public class Main {

    public static void main(String[] args) throws IOException
    {
        String qstring = "SELECT * FROM comments";
        new DB(qstring).readFromDatabase();
        System.in.read();
    }

}

1 个答案:

答案 0 :(得分:3)

您在驱动程序类名称中输入了错字。

private String driverClassName = "com.myqsl.jdbc.Driver";

应该是

private String driverClassName = "com.mysql.jdbc.Driver";
// -------------------------------------^

对于具体问题,

无关,将ConnectionStatementResultSet等数据库资源作为类的实例变量是一个坏主意。您需要在try-finally块中尽可能短的时间内创建,使用和关闭它们,以防止资源泄漏。另请参阅此问题/答案:When my app loses connection, how should I recover it?