用JSP查看所有Mysql数据库

在根目录新建文件mysql_list.jsp,代码如下:

<%@ page import="java.sql.*" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>显示所有MySQL数据库</title>
</head>
<body>
<%
    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;
    try {
        // 加载并注册JDBC驱动
        Class.forName("com.mysql.jdbc.Driver");
 
        // 建立连接,端口、用户名、密码
        conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/?user=root&password=root");
 
        // 创建Statement对象执行查询
        stmt = conn.createStatement();
        rs = stmt.executeQuery("SHOW DATABASES");
 
        // 处理结果集
        while (rs.next()) {
            out.println(rs.getString(1) + "<br>");
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        // 关闭资源
        try {
            if (rs != null) rs.close();
            if (stmt != null) stmt.close();
            if (conn != null) conn.close();
        } catch (SQLException se) {
            se.printStackTrace();
        }
    }
%>
</body>
</html>

需要根据你的mysql系统,修改一下用户名、密码

文章导航