Class.forName(“com.mysql.jdbc.Driver”).newInstance()

前端 未结 4 877
盖世英雄少女心
盖世英雄少女心 2020-12-18 14:14

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.

prot         


        
4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-18 15:08

    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:

    
    
    
    

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

    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 /lib folder.

提交回复
热议问题