richzilla
richzilla

Reputation: 41982

why can't java see my mysql driver

I'm having trouble working out why java can't see my mysql driver:

But I'm still getting ClassNotFound Exceptions. Is there anything else I need to be doing?

class example:

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);
        }
    }



}

My main class simply passes the query into the DB class:

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();
    }

}

Upvotes: 0

Views: 108

Answers (1)

BalusC
BalusC

Reputation: 1108692

You've a typo in the driver class name.

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

it should be

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

Unrelated to the concrete problem, holding DB resources like Connection, Statement and ResultSet as an instance variable of the class is a bad idea. You need to create, use and close them in the shortest possible scope in a try-finally block to prevent resource leaking. See also among others this question/answer: When my app loses connection, how should I recover it?

Upvotes: 3

Related Questions