写了一个jsp页面就能对数据库某个数据进行更改
index.jsp页面如下:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page language="java" %>
<%@ page import="com.mysql.jdbc.Driver" %>
<%@ page import="java.sql.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<script type="text/javascript">
<%
String file=request.getParameter("lujing_url");
if(file!=null && file!=""){
String url="jdbc:mysql://127.0.0.1/dzbl_type?user=root&password=123456";
Class.forName("com.mysql.jdbc.Driver");
Connection conn=DriverManager.getConnection(url);
Statement stmt = conn.createStatement();
String sql="update bas_dicts set option01 = "+file+" where dictid = '201708071'";
stmt.executeUpdate(sql);
stmt.close();
conn.close();
}
%>
</script>
<body>
<form action="index.jsp" method="post" name="">
<input type="text" id="lujing_url" name="lujing_url"/>
<input type="submit" id="tijiao" value="提交" />
</body>
</html>
说明:
1.body里写了一个form表单,一个文本输入框(name=“lujing_url”),一个提交按钮。
2.点击提交按钮后,将文本框的内容发送到index.jsp页面,这时执行java代码,接收到name=“lujing_url”的数据
3.判断下接收的数据不为空后对数据库进行操作。(前提必要的jar包是必要的)
注:java代码块一定要写判断是否为空语句,jsp页面中首先执行java代码块,不写判断语句会导致页面一加载就会更新数据库,而不是等你按了提交按钮再去执行。
原理:
jsp中的java代码 —— 服务器端代码
js代码 —— 客户端代码
java是在服务器端运行的代码,jsp在服务器的servlet里运行,而javascript和html都是在浏览器端运行的代码。
所以服务器端先执行,执行后将信息传给客户端。
因此加载jsp页面的执行顺序是java -> jsp ->js,
加载jsp的时候先编译java代码,有错误的话会直接报错;没报错的话会执行jsp代码,最后加载js代码。
---------------------------------------------------------------------------------------------------------------------end