现在的位置: 首页 > 综合 > 正文

如何用一张JSP页面连接数据库,实现查询、修改操作

2017年10月11日 ⁄ 综合 ⁄ 共 1490字 ⁄ 字号 评论关闭

1、在Oracle数据库中创建表sparametertbl

2、在JSP页面中写代码

<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<%@ page import="java.sql.*"%>  <!--   添加java的sql包 -->
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>加载页面</title>
</head>
<body>

<%Class.forName("oracle.jdbc.driver.OracleDriver").newInstance(); //加载Oracle数据库的驱动   
  String url="jdbc:oracle:thin:@localhost:1521:orcl";       //添加Oracle的连接地址,localhost即默认本机地址
  String user="student";  //数据库的帐号
  String password="student";//数据库的密码
  Connection conn= DriverManager.getConnection(url,user,password);   //将url,user和password实现数据库的连接 
  Statement stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);//实例化Statement对象    
  String sql="select * from sparametertbl t where t.PARAMETER='autoChecking' "; //查询语句   
  String sql2="update  sparametertbl t set t.value='0'   where t.parameter='autoChecking'";//修改语句1
  String sql3="update  sparametertbl t set t.value='1'   where t.parameter='autoChecking'";//修改语句2
  ResultSet rs=stmt.executeQuery(sql);  //执行查询操作
  String flag="";
     while(rs.next()) { //利用循环获取结果集的数据
       flag=rs.getString(2);
                      }   
  String show="";
     if(flag.equals("1")){//当结果是1的时候置换成0
	   stmt.executeUpdate(sql2);//执行修改操作
	   show="关闭";
	   flag="0";
     }else{           //当结果是0的时候置换成1
	   stmt.executeUpdate(sql3);//执行修改操作
	   show="开启";
	   flag="1";   
     }
  rs.close();   //关闭rs
  stmt.close();  //关闭操作
  conn.close(); //关闭连接   
%>  
当前自动检测的状态是:<%=show%> <%=flag%> 
</body>
</html>

3、最后效果:因为Value值为0,开始页面显示0,关闭。刷新一次页面,执行了SQL修改操作,Value值被置成1,开启。

 

抱歉!评论已关闭.