代码之家  ›  专栏  ›  技术社区  ›  Ankur

连接到Mac上的MySql:没有合适的驱动程序错误

  •  1
  • Ankur  · 技术社区  · 16 年前

    我得到了错误:java.sql.SQLException:没有合适的驱动程序

    我已经导入了这里提供的.jar文件 http://dev.mysql.com/downloads/mirror.php?id=13598

    我正在使用Eclipse。

    我使用以下代码连接到数据库:

    package dao;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    
    public class DBCon {
    
        private static final String host = "jdbc:mysql://localhost";
        private static final String port = "3306";
        private static final String db = "mydb";
    //      private static final String user = "root";
    //      private static final String pwd = "";
        private static final String user = "myusername";
        private static final String pwd = "mypwd";
    
        public Connection getCon() {
            Connection con = null;
            try {
                String url = host + ":" + port + "/" + db;
    
                con = DriverManager.getConnection(url, user, pwd);
    
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return con;
        }
    }
    

    然后我用以下代码查询数据库:

    package dao;
    
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.ArrayList;
    import java.sql.Connection;
    import model.ClassPojo;
    
    public class ARCSDao {
    
    public ArrayList<ClassPojo> viewClasses() throws SQLException{
        ArrayList<ClassPojo> classList = new ArrayList<ClassPojo>();
    
        DBCon db = new DBCon();
        Connection con = db.getCon();
        Statement stmt;
        ResultSet rs;
        stmt = con.createStatement();
        rs = stmt.executeQuery("SELECT * FROM classes");
        while(rs.next()){
               ClassPojo aClass = new ClassPojo();
               rs.getString("class_name");
               rs.getString("class_uri");
               classList.add(aClass);
        }           
        return classList;
        }
    }
    
    1 回复  |  直到 16 年前
        1
  •  2
  •   stacker    16 年前

    添加

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

    之前

    con = DriverManager.getConnection(url, user, pwd);
    

    如果这不起作用,请仔细检查类路径中是否包含jdbc驱动程序(jar文件)