JSP Connecting to MySQL

We use tomcat as the container used for instructions in the post.

1) Download the driver mysql-connector-java-*.*.*-bin.jar and put it into WEB-INF/lib/, and remember to restart tomcat.

2) The example code as follows.

    String driverName="com.mysql.jdbc.Driver";
    
    String userName="username";
    
    String userPasswd="password";
    
    String dbName="dbname";
    
    String tableName="tablename";
    
    String url="jdbc:mysql://localhost/"+dbName+"?user="+userName+"&password="+userPasswd;
    
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    Connection conn=DriverManager.getConnection(url);
    Statement statement = conn.createStatement();
    String sql="SELECT * FROM "+tableName;
    ResultSet rs = statement.executeQuery(sql);
    
    // get the result
    ResultSetMetaData rmeta = rs.getMetaData();
    
    // the the number of columns
    int numColumns=rmeta.getColumnCount();
    
    // out each field
    while(rs.next()) {
        out.print(rs.getString(1)+" ");
        out.print("|");
        out.print(rs.getString(2));
        out.print("
    ");
    }
    
    out.print("
    ");
    out.print("Operations on the DB is done.");
    rs.close();
    
    statement.close();
    conn.close();

Eric Zhiqiang Ma

Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

Leave a Reply

Your email address will not be published. Required fields are marked *