java - JDBC 类未找到异常

标签 java mysql bash ubuntu jdbc

我最近开始使用 JDBC。我从 ubuntu 软件中心安装了 JDBC 驱动程序,并使用 JDBC 运行我的第一个 java 程序。

import java.sql.*    
public class db
{
    static final String JDBC_DRIVER="com.mysql.jdbc.Driver";
    static final String DB_URL="jdbc:mysql://localhost/emp";
    static final String USER= "username";
    static final String PASS="password";
    public static void main(String [] args)
    {
        Connection conn=DriverManager.getConnection(JDBC_DRIVER);
        Statement stmt=null;
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            System.out.println("Connecting to database");
            System.out.println("Creting statement");
            String sql;
            stmt=conn.createStatement();
            sql="select id, first last, age from Employee";
            ResultSet rs= stmt.executeQuery(sql);
            while(rs.next())
            {
                int id=rs.getInt("id");
                int age=rs.getInt("age");
                String first=rs.getString("first");
                String last=rs.getString("Last");
                System.out.print("ID: "+id);
                System.out.print(", Age: " +age);
                System.out.print(", First: "+first);
                System.out.println(", Last: "+last);
            }
            rs.close();
            stmt.close();
            conn.close();
        }
        catch(SQLException se)
        {
            se.printStackTrace();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                if(stmt!=null)
                    conn.close();
            }
            catch(SQLException se)
            {
                se.printStackTrace();
            }
        }
    }
}

我创建了“emp”数据库​​,并尝试使用 JDBC 浏览其内容。当我使用时

javac db.java

一切正常。但是当我通过

运行它时
java db

它给了我 java.lang.classnotfoundException。我将 CLASSPATH=CLASSPATH://user/share/java/mysql-connector-java.jar 包含到 bashrc 文件中。谁能帮我解决这个问题吗?

最佳答案

  • Class.forName("com.mysql.jdbc.Driver"); 放在 DriverManager.getConnection() 调用之前,而不是之后
  • DriverManager.getConnection() 需要 URL 作为参数,而不是驱动程序类名,因此使用 Connection conn=DriverManager.getConnection(DB_URL);

关于java - JDBC 类未找到异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34043677/

相关文章:

java - 文档 - 它是一个模板吗?

mysql:一次查询更新多条记录

php - 如何将计算排名结果制作成表格?

linux - 从脚本启动的终端中的救援错误

java - 使部署失败并出现 Glassfish 3.1 中的自定义错误

java - CodeModel 修饰符顺序

python - 从 python 子进程模块启动模块 shell 命令

linux - awk 或 bc 哪个对于浮点运算更有效?

java - 如何为 Android 创建 Java 应用程序。问题

python - Mysql - 如何将skip_networking设置为关闭?