时间:2021-07-01 10:21:17 帮助过:11人阅读
我们再来看LoginServlet.java的内容:
import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;@WebServlet(name = "LoginServlet")public class LoginServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String username = request.getParameter("username"); System.out.println("username="+username); String userpwd = request.getParameter("userpwd"); System.out.println("userpwd="+userpwd); PreparedStatement statement=null; ResultSet resultSet=null; //1.不采用数据源连接池,需要频繁建立与数据库的连接与释放资源 Connection connection = UtilJDBC.openConnection(); try { statement=connection.prepareStatement("SELECT * FROM users where username=? AND userpwd=?"); statement.setString(1,username); statement.setString(2,userpwd); resultSet = statement.executeQuery(); if(resultSet.next()){ System.out.println("登录成功!"); }else{ System.out.println("登录失败!"); } } catch (SQLException e) { e.printStackTrace(); }finally { Util_1_JDBC.release(connection,statement,resultSet); }}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); }}另外,数据库名称为itszt2,要访问的表users的结构为:
CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(20) NOT NULL, `userpwd` varchar(20) NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;该表中存了一条数据,即(“xiaoming”,123456)。
读者可以在自己的电脑上对上述代码进行测试,以观察数据库连接,以及练习sql语句的若干操作。
JavaWeb之原生数据库连接
标签:mysq connect 用户名 where throw mapping prot 连接池 out