柯侧耳倾听者 - 云代码空间
—— 翱翔在Java世界的海洋之上
一、实验目的 熟练掌握数据库操作的基本步骤,逐步理解掌握DAO模式的定义及使用。
二、预习内容及要求(要求写出预习内容) (1)JDBC数据库连接Jar包的下载及导入、Mysql数据库的简单使用; (2)数据库操作的步骤。加载JDBC、建立连接所需的三个参数、建立连接、创建语句、执行SQL、得到结果集等; (3)执行查询与更新的方法差别、不带与带参数的差别、结果的获取等
三、实验内容、操作过程及实验结果记录 实验题目:编写通信录程序,要求: 1.应具有注册、登录功能,并可以实现用户好友的查询和添加功能,不需要实现修改和删除。 2.注册页面为RegisterForm.jsp,登录页面为loginForm.jsp,登录之前不能访问与注册、登录无关的页面。登录和注册功能应由register.jsp和login.jsp实现。 3.使用JSP+Servlet+MySql+JDBC实现
JDBC: public class DButil { private static Connection con = null; //获取连接 public static Connection getConnection(){ //1.加载数据库驱动 try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { System.out.println("加载失败!"); e.printStackTrace(); } System.out.println("加载成功!"); //2.连接数据库 try { con=DriverManager.getConnection("jdbc:mysql://localhost:3306/db_library", "root", "123"); } catch (SQLException e) { System.out.println("连接数据库失败!"); e.printStackTrace(); } System.out.println("成功连接数据库!"); return con; } //关闭连接 public static void closeConnection() { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } } try { statement = con.createStatement(); int id1=5; String name1="李四2"; int age1 = 24; int i = statement.executeUpdate("insert into table1(name,age) values('"+name1+"','"+age1+"')"); System.out.println(i); System.out.println("添加成功!"); } catch (SQLException e) { System.out.println("执行sql语句出错!"); e.printStackTrace(); return; }
JSP代码 <body> <center> <h2>学生信息管理系统</h2> </center> <hr/> <% int count=Integer.parseInt(application.getAttribute("access_count").toString()); count++; %> 当前访问次数:<%=count %> <% application.setAttribute("access_count",count); %> <%-- 在服务器启动之时,读取数据库存储的数据, 只要访问主页,就需要将ServletContext中的access_count作加1操作, 再显示在页面上 退出Web应用时,将access_count写入到数据库表中 --%> <br> 欢迎您,<%=session.getAttribute("userName") %> <br><br> 当前用户列表<br> <% List list=(List)application.getAttribute("userList"); for (Object o:list){ out.println((String)o); out.println("<br/>"); } System.out.println(session.getAttribute("userName")); %> <hr/> <a href="LogoutAction" >退出</a> </body>
四、实验过程中所遇问题思考与讨论(可写个人体会,或相关理论知识,根据个人具体情况选做) 通过这次的学习与实验,我进一步掌握了JavaWeb中有关JavaBean和Servlet技术的一些方法,也更加了解了JavaBean和Servlet技术的概念,为今后更好的学习JavaWeb做好铺垫,在学习的过程中,我更加深刻的体会到与老师和同学间的交流与合作是多么的重要,所以在今后的学习与实验当中,我们要善于发现问题,更要及时与老师反馈问题所在,并与老师和同学交流学习经验,共同解决问题,这样才能更好的学好JavaWeb这门课程。
|