JSP脚本连接数据库

入门

简单的jsp文件

<%--
  Created by IntelliJ IDEA.
  User: e550
  Date: 2017/1/9
  Time: 23:24
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" import="java.util.*" language="java" %>

<html>
<head>
    <title>欢迎</title>
</head>
<body>
欢迎学习Java web知识!
现在的时间是:
<%out.println(new java.util.Date());%>
</body>
</html>

声明

<%--
  Created by IntelliJ IDEA.
  User: e550
  Date: 2017/1/9
  Time: 23:24
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" import="java.util.*" language="java" %>

<html>
<head>
    <title>声明示例</title>
</head>
<%!
    // 声明一个整型变量
    public int count;
    // 声明一个方法
    public String info() {
        return "hello java";
    }
%>


<body>
<%
    // 输出变量
    out.println(++count); // 加1后输出1
    // 输出方法的返回值
    out.println(info());
%>
</body>
</html>

变量输出

<%--
  Created by IntelliJ IDEA.
  User: e550
  Date: 2017/1/9
  Time: 23:24
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" import="java.util.*" language="java" %>

<html>
<head>
    <title>输出表达式</title>
</head>
<%!
    // 声明一个整型变量
    public int count;
    // 声明一个方法
    public String info() {
        return "hello java";
    }
%>


<body>
<%=
count++
%>

<%=
info()
%>
</body>
</html>

小脚本测试

<%--
  Created by IntelliJ IDEA.
  User: e550
  Date: 2017/1/9
  Time: 23:24
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" import="java.util.*" language="java" %>

<html>
<head>
    <title>小脚本测试</title>
</head>


<body>
<table bgcolor="#bdb76b" border="1" width="300px">
    <%
        for(int i=0;i<10;i++) {
    %>
        <tr>
            <td>循环值:</td>
            <td><%=i%></td>
        </tr>
    <%
        }
    %>
</table>
</body>
</html>

连接数据库

<%--
  Created by IntelliJ IDEA.
  User: e550
  Date: 2017/1/9
  Time: 23:24
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8"  language="java" errorPage="" %>
<%@ page import="java.sql.*" %>

<html>
<head>
    <title>小脚本测试</title>
</head>


<body>
<%
    // 注册数据库驱动
    Class.forName("com.mysql.jdbc.Driver");
    // 获取数据库连接
    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test_mysql","root","123456");
    // 创建Statement
    Statement stmt = conn.createStatement();
    // 执行查询
    ResultSet rs = stmt.executeQuery("select * from tp_goods_type;");
%>
<table bgcolor="#bdb76b" border="1px" width="300px">
    <%
        // 遍历结果集
        while (rs.next())
        {
    %>
    <tr>
        <td>
            <%= rs.getString(1)%>
        </td>
        <td>
            <%= rs.getString(2)%>
        </td>
    </tr>
    <%
        }
    %>

</table>
</body>
</html>

这里注意了,需要在编辑器中配置,

否则无法连接数据库!

原文地址:https://www.cnblogs.com/jiqing9006/p/6332097.html