数据库的预处理

//学习数据库的预处理方式
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException
	{
		//从表单获取相应的值
		String userName=req.getParameter("name");
		String password=req.getParameter("password");
		
		//建立一个连接
		Connection connection=null;
		//一个连接(预处理方式)的状态
		PreparedStatement statement=null;
		//结果集
		ResultSet resultSet=null;
		
		//注意预处理的时的值得传递,一个值用一个问号代替
		String sql="select count(id) from info where Uname= ? and password= ?";
		
		 
		try
		{
			//加载数据库
			Class.forName("com.mysql.jdbc.Driver");
			//连接字符串
			String url="jdbc:mysql:///person";
			//用户名
			String user="root";
			//密码
			String password2="123456";
			try
			{
				connection=DriverManager.getConnection(url, user, password2);//得到连接
				statement=connection.prepareStatement(sql);//
				statement.setString(1, "dengchao"); //设置参数,有几个问号就设置几个参数,与之相对应
				statement.setString(2, "123123");
				resultSet=statement.executeQuery();//预处理的查询,,注意没有任何参数,,
				PrintWriter out=resp.getWriter();
				if(resultSet.next())
				{
					int n=resultSet.getInt(1);
					if(n>0)
						out.print("hello  "+userName );
					else out.print("sorry "+userName);
				}
				statement.close();
				connection.close();
				
			} catch (SQLException e)
			{
				e.printStackTrace();
			}
		
			
			
		} catch (ClassNotFoundException e)
		{
			e.printStackTrace();
		}
		
		
	}
posted @ 2017-04-14 19:07  -梦里不知身是客  阅读(230)  评论(0编辑  收藏  举报