一个简单的JSP链接Mysql数据库的例子

这个例子是描述在mysql里有pubs数据库,数据库里有个authors表,jsp链接数据库,在网页里用table将其组织打印出来(其中每个作者的ID号没有打印):

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<%@ page contentType="text/html; charset=gb2312" %>
<%@ page language="java" %>
<%@ page import="com.mysql.jdbc.Driver" %>
<%@ page import="java.sql.*" %>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>Task3.jsp</title>
</head>
   
<body>
    <form method="post" action="t3_result.jsp" name="form1" >
    请输入要查询者的姓名:<input type="text" name="name" size="20" />
    <input type="submit" name="submit" />
    </form>
    <%
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost/pubs", "root", "admin");
        Statement statement = con.createStatement();
        ResultSet rs = statement.executeQuery("select name, phone, addr from authors");
        ResultSetMetaData rmeta = rs.getMetaData();
        int numColumns=rmeta.getColumnCount();
        out.print("<table border='1'>");
        while (rs.next()) {
            out.print("<tr>");
            for (int i = 1; i <= numColumns; i++) {
                out.print("<td>");
                out.print(rs.getString(i));
                out.print("</td>");
            }
            out.print("</tr>");
        }
        out.print("</table><br>");
        con.close();
    %>
</body>
</html>

你可能感兴趣的:(数据库,jsp,mysql,XHTML,import)