20151205--JDBC-2

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>
<script type="text/javascript">
function yanz()
{
    if  (zhugan.userid.value == "")
        {
            alert("用户代码不能为空!");
            return false;
        }
    if(zhugan.username.value == "")
        {
            alert("用户名称不能为空!");
            return false;
        }
    if(zhugan.password.value == "")
        {
        alert("登陆密码不能为空!");
        return false;
        }
    /*
    if(zhugan.passwore.value == "")
        {
            alert("确认密码不能为空!");
            return false;
            }
    */
    if(zhugan.password.value != zhugan.passwore.value)
    {
        alert("登陆密码与确认密码不相同!");
        return false;
    }
return true;
}
</script>
</head>
<body>
<form id="zhugan" action="SaveUser"  method="get"  onSubmit="return yanz();">
用户代码:<input id="userid" type="text" name="userid" width=30 />
<br><br>
用户名称:<input id="username" type="text" name="username" width=30 />
<br><br>
登录密码:<input id="password" type="password" name="password" width=30 />
<br><br>
确认密码:<input id="passwore" type="password" name="pueren" width=30 />
<br><br>
<input type="submit" value="提交" />
</form>
</body>
</html>

注册页面

package com.hanqi;

import java.io.IOException;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class SaveUser
 */
public class SaveUser extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public SaveUser() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");

        response.setContentType("text/html;charset=UTF-8");

        response.setCharacterEncoding("UTF-8");

        //获取内容
        String userID = request.getParameter("userid");
        String userName = request.getParameter("username");
        String pw = request.getParameter("password");

        //判断输入的内容
        if(userID == null || userID.trim().length() == 0)
        {
            //输出内容
            response.getWriter().append("用户代码不能为空");
        }
        else if(userName == null || userName.trim().length() == 0)
        {
            response.getWriter().append("用户姓名不能为空");
        }
        else
        {
            try
            {
                //加载数据库驱动,并注册到驱动管理器
                Class.forName("oracle.jdbc.driver.OracleDriver");
                //数据库连接字符串
                String url = "jdbc:oracle:thin:@localhost:1521:orcl";
                //获取connection对象 (个人理解为登陆数据库 并将数据关联)
                Connection conn = DriverManager.getConnection(url,"test","123654789");    //url,名称,密码
                //判断是否有数据
                if(conn != null)
                {
                    //操纵数据库
                    String sql = "insert into t_user (user_id,user_name,password) "
                            + "values (?,?,?)";
                    //另外一种方法:
                    //String sql = "insert into t_user (user_id,user_name,password) values (‘" + userID + "‘)";

                    //执行sql语句的类
                    PreparedStatement pps = conn.prepareStatement(sql);
                    //转码
                    //userName = new String(userName.getBytes("ISO-8859-1"),"UTF-8");      post 提交方式不用转码  get方式需要转码
                    //将操纵数据库中数据类名编下顺序便于输入
                    pps.setString(1, userID);
                    pps.setString(2, userName);
                    pps.setString(3, pw);

                    int row = pps.executeUpdate();     //执行sql语句并返回所影响的行数

                    if(row > 0)
                    {
                        response.getWriter().append("保存"+ row +"条数据成功");
                    }
                    else
                    {
                        response.getWriter().append("保存数据失败");
                    }
                    //关闭  释放资源
                    pps.close();

                    conn.close();

                }
                else
                {

                }

            }
            catch (ClassNotFoundException e)        //仅捕获一类特定异常
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
                response.getWriter().append(e.getMessage());
            }
            catch (Exception e)                     //捕获所有异常
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
                response.getWriter().append(e.getMessage());
            }

        }
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

SaveUser

package com.hanqi;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class FindUserList
 */
public class FindUserList extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public FindUserList() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");    

        try
        {
            //加载数据库驱动,并注册到驱动管理器
            Class.forName("oracle.jdbc.driver.OracleDriver");
            //数据库连接字符串
            String url = "jdbc:oracle:thin:@localhost:1521:orcl";
            //获取connection对象 (个人理解为登陆数据库 并将数据关联)
            Connection conn = DriverManager.getConnection(url,"test","123654789");    //url,名称,密码
            //判断是否有数据
            if(conn != null)
            {
                //操纵数据库
    //            String sql = "insert into t_user (user_id,user_name,password) "
    //                    + "values (?,?,?)";
                String sql = "select * from t_user";
                //另外一种方法:
                //String sql = "insert into t_user (user_id,user_name,password) values (‘" + userID + "‘)";

                //执行sql语句的类
/*
                  PreparedStatement pps = conn.prepareStatement(sql);
*/
                Statement stm = conn.createStatement();
                //执行查询,返回结果集
                ResultSet rs = stm.executeQuery(sql);
                //数组的方式来进行  装载  和  传输
                ArrayList<User> array = new ArrayList<User>();//将数据装载在数组中放置到其他地方进行输出

                if(rs != null)
                {
                    //遍历结果集
                    while(rs.next())
                    {
                        //实体类装载记录
                        User u  = new User();
                        u.setUserid(rs.getString("USER_ID"));
                        u.setUsername(rs.getString("USER_NAME"));
                        u.setPassword(rs.getString("PASSWORD"));

                        /*
                        //取值 要按照相应类型来取
                        rs.getString("");        // 按字段名来取
                        rs.getString(0);        // 括号内 columnIndex 是 列的序号 字段序号是从  1  开始算的
                        rs.getDouble(0);        //注意要取值的类型
                        */

                        //将装载的数据传输
                        array.add(u);
                        response.getWriter().append("USER_ID = "+ rs.getString("USER_ID")+";<br>");
                        response.getWriter().append("USER_NAME = "+ rs.getString("USER_NAME")+";<br>");
                        response.getWriter().append("PASSWORD = "+ rs.getString("PASSWORD")+";<br>");

                    }
                    request.setAttribute("userlist", array);

                    //释放
                    rs.close();
                }
                else
                {
                    response.getWriter().append("结果集为空");
                }
                //关闭  释放资源
                stm.close();

                conn.close();

            }
            else
            {

            }

        }
        catch (ClassNotFoundException e)        //仅捕获一类特定异常
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
            response.getWriter().append(e.getMessage());
        }
        catch (Exception e)                     //捕获所有异常
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
            response.getWriter().append(e.getMessage());
        }
        //页面跳转
        request.getRequestDispatcher("ShowUserList.jsp").forward(request,response);

    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

FindUserList

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ page import="java.util.*" %>
    <%@ page import="com.hanqi.*" %>
<!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>用户列表   先启动FindUserList</title>
</head>
<body>
<%

Object obj = request.getAttribute("userlist");

if(obj != null)
{
    ArrayList<User> array = (ArrayList<User>)obj;

    //遍历
    for(User u : array)
    {
        out.print(u.getUserid() + "\t" + u.getUsername() + "\t" + u.getPassword() + "<br>");
    }

}
else
{
    out.append("用户列表为空");
}

%>
</body>
</html>

ShowUserList

时间: 2024-10-28 20:24:40

20151205--JDBC-2的相关文章

jdbc的简单使用

1.加载驱动(mysql的驱动是com.mysql.jdbc.Driver,SqlServer的驱动是 com.microsoft.sqlserver.jdbc.SQLServerDriver) 2.加载数据库的连接(url, username,password) 3.编写sql语句(String sql="select * from grade  where gradeName = ?";) 4.遍历查询结果 [while (resultSet.next()) {   System.

商城项目整理(三)JDBC增删改查

商品表的增加,修改,删除,订单表的增加,确认,用户表的查看,日志表的增加,查看 商品表建表语句: 1 create table TEST.GOODS_TABLE 2 ( 3 gid NUMBER not null, 4 gname VARCHAR2(90), 5 gdetails CLOB, 6 gpicture VARCHAR2(100), 7 gprice NUMBER, 8 gleixing NUMBER, 9 gpinpai VARCHAR2(20) 10 ) 11 tablespace

jdbc驱动jar导入eclipse

在使用JDBC编程时需要连接数据库,导入JAR包是必须的,导入其它的jar包方法同样如此,导入的方法是 打开eclipse 1.右击要导入jar包的项目,点properties 2.左边选择java build path,右边选择libraries 3.选择add External jars 4.选择jar包的按照路径下的确定后就行了. Java连接MySQL的最新驱动包下载地址 http://www.mysql.com/downloads/connector/j 有两种方法导入jar包,第一种

JDBC

Java语言访问数据库的一种规范,是一套API JDBC (Java Database Connectivity) API,即Java数据库编程接口,是一组标准的Java语言中的接口和类,使用这些接口和类,Java客户端程序可以访问各种不同类型的数据库.比如建立数据库连接.执行SQL语句进行数据的存取操作. JDBC规范采用接口和实现分离的思想设计了Java数据库编程的框架.接口包含在java.sql及javax.sql包中,其中java.sql属于JavaSE,javax.sql属于JavaE

java链接MySQL数据库时使用com.mysql.jdbc.Connection的包会出红线问题

package com.swift; //这里导入的包是java.sql.Connection而不是com.mysql.jdbc.Connection import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class TestJDBC { public static void main(String[] args) { try { Class.forName(

Tomcat JDBC Pool使用说明

Maven依赖 <dependency>   <groupId>org.apache.tomcat</groupId>   <artifactId>tomcat-jdbc</artifactId>   <version>8.5.9</version> </dependency> 最新版本为9.0,推荐使用8.5.9稳定版 常用配置 连接池配置项很多,下面只列出了推荐配置,项目组可根据自身情况进行增减 <b

tomcat启动过程报the JDBC Driver has been forcibly unregistered问题的修复过程

最近两天在整理关于flume的总结文档,没有启动过tomcat.昨天晚上部署启动,发现报了如题的错误,全文如下: 严重: The web application [/oa-deploy] registered the JBDC driver [com.microsoft.sqlserver.jdbc.SQLServerDriver] but failed to unregister it when the web application was stopped. To prevent a mem

使用JDBC如何提高访问数据库的性能?

1. 使用数据连接池(Connection Pool), 避免使用DriverManager.getConnection. 2. 合理的配置数据连接池参数,设置数据连接池的初始大小,最大连接数,连接超时时间等. 3. 选择合适的事务等级,按照不同的数据库操作类型选择不同的事务等级. 4. 及时关闭Connection,不关闭的话会严重影响系统的性能,甚至造成系统罢工. 5. 优化Statement 1) 选择合适的Statement, 根据不同的数据库操作选择Statement, Prepare

回滚的意义---JDBC事务回滚探究

JDBC手动事务提交回滚的常见写法一直是rollback写在commit的catch之后: try{ conn.setAutoCommit(false); ps.executeUpdate(); ps.executeUpdate(); conn.commit(); }catch(Exception e){ conn.rollback(); } 但是,这种回滚是没有意义的: 一旦commit前出错, 就不提交了, 回滚无用 一旦commit了, 说明没错, 不用回滚 找到一篇和我观点相同的文章:

Hive JDBC——深入浅出学Hive

第一部分:搭建Hive JDBC开发环境 搭建:Steps ?新建工程hiveTest ?导入Hive依赖的包 ?Hive  命令行启动Thrift服务 ?hive --service hiveserver & 第二部分:基本操作对象的介绍 Connection ?说明:与Hive连接的Connection对象 ?Hive 的连接 ?jdbc:hive://IP:10000/default" ?获取Connection的方法 ?DriverManager.getConnection(&q