在jsp中连接数据库并显示其内容

作者:陈世佳  编写时间:2018-3-20

方法如下:

    步骤一:下载tomcat源文件

    步骤二:下载mysql-connector-java-5.1.26-bin.jar资源(连接数据库必备的jar包),并且移至tomcat文件的lib目录下。

    步骤三:编写index.jsp文件,内容如下,并且替换掉tomcat文件的webapps\ROOT目录下的index.jsp文件。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*"%> <%--导入的mysql驱动包--%>

<html>
<head>
    <meta charset="utf-8">
	<title>jsp之连接数据库</title>
</head>
<body >
<%
    //加载驱动程序
    String driverName="com.mysql.jdbc.Driver";
    //数据库连接
    String url="jdbc:mysql://www.lemoncollege.com:3306/student?useUnicode=true&characterEncoding=UTF-8";
    //数据库信息
    //用户名
    String userName="test";
    //密码
    String userPasswd="123456";
    //数据库名
    String dbName="student";
    //表名
    String tableName="student";
    //将数据库信息字符串连接成为一个完整的url(也可以直接写成url,分开写是明了可维护性强)

    Class.forName("com.mysql.jdbc.Driver");
    Connection conn = DriverManager.getConnection(url, userName,userPasswd);// 连接数据库
    Statement statement = conn.createStatement();// statement用来执行SQL语句
    ResultSet rs = statement.executeQuery("select * from student limit 20");//获取结果
%>
<%
    String student_id;
    String student_name;
    String student_sex;
    String class_id;
    String birthday;
    String birth_place;
    String political_status;
    rs.last();
    int intCount=rs.getRow();
    rs.beforeFirst();
%>
<p>
    总条数:<%=intCount%>
</p>
<center>
    <table border="3" width="95%">
        <tr>
            <td>学生学号</td>
            <td>学生姓名</td>
            <td>学生性别</td>
            <td>班级编号</td>
            <td>生日</td>
            <td>籍贯</td>
            <td>政治面貌</td>
        </tr>
        <%
            while(rs.next()){
                student_id = rs.getString(1) ;
                student_name = rs.getString(2) ;
                student_sex = rs.getString(3) ;
                class_id = rs.getString(4) ;
                birthday = rs.getString(5) ;
                birth_place = rs.getString(6) ;
                political_status = rs.getString(7) ;

        %>
        <tr>
            <td><%=student_id%></td>
            <td><%=student_name%></td>
            <td><%=student_sex%></td>
            <td><%=class_id%></td>
            <td><%=birthday%></td>
            <td><%=birth_place%></td>
            <td><%=political_status%></td>
        </tr>
        <%
            }
        %>
    </table>
</center>
</body>
<html>

   步骤四:双击bin目录下的stratup.bat后,打开浏览器,输入localhost:8080,能看到图1即表示连接数据库成功,双击shutdown.bat关闭tomcat。


图1

    资源下载:输入3v11,下载已经封装好的连接数据库模板压缩包,并解压,https://pan.baidu.com/s/1_QSheosGesnPVKiM7Xe8GA点击打开链接


发布了20 篇原创文章 · 获赞 20 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/csj41352/article/details/79624410