初识JSP

JSP刚开始学,使用MyEclipse开发比JCreator高效了不少,记得开启tomcat服务器,并将工程发布上去就可以,今天要写一个简单的用户登录界面,主要知识是jsp语法,jdbc连接mysql,以及页面跳转。在mysql驱动加载时遇到了一些问题

加载数据库驱动时

//ct = DriverManager.getConnection("jdbc:mysql://localhost:3306/jtdb1","root","jiangtao123");
   ct = DriverManager.getConnection("jdbc:mysql://localhost:3306/jtdb1?user=root&password=jiangtao123");

两种方法都是可以的。

在创建语句时

pst = ct.prepareStatement("select * from StuManagement where stuname = '"+username+"'");

 注意变量 username的写法:'"+XXX+"'

当然,使用?的方法也是可以的

pst = ct.prepareStatement("select * from StuManagement where stuname = ?");
pst.setString(1, username);

 起初,在用户名验证的时候,想法是使用pst.executeUpdate()方法,得到一个int值,来判断是否有这个用户,如果有,返回1,否则是0;但是报错,

java.sql.SQLException: Can not issue executeUpdate() or executeLargeUpdate() for SELECTs

查了一下,发现select语句一般不用executeUpdate方法,而是用execute(),或者executeQueue(),但是execute()方法返回的是布尔值,只要语法正确就可以,不能作为判断,所以只能使用ResultSet 和 executeQueue()的办法。

之后就是验证用户名和密码,

if(dbrs.next())
   	{
   		System.out.println("密码是"+password);
   		//pst2 = ct.prepareStatement("select * from StuManagement where stuage = '"+password+"'");
   		//pst.setInt(1, Integer.parseInt("password"));
   		//pst2.executeUpdate();
   		
   		if(password.equals(dbrs.getInt(3)+""))
   			response.sendRedirect("Welcome.jsp?use="+username);
   		else
   			response.sendRedirect("Login.jsp");
   		
   	}
   	else
   	{
   		response.sendRedirect("Login.jsp");
   	}
   }

  页面的跳转和共享数据使用的是简单的

response.sendRedirect("Welcome.jsp?use="+username);

  最后需要注意的是关闭资源

finally
   {
   	try{
   	pst.close();
   	
   	ct.close();
   	}
   	catch(Exception e)
   	{
   		e.printStackTrace();
   	}
   }

  之后需要验证的就是,pst作为一个PreparedStatement变量,如果执行多条sql语句,之间会有影响吗?

原文地址:https://www.cnblogs.com/TaoChiangBlog/p/5953662.html