mysql数据库怎么连接数据库_简单的MySQL数据库连接例子

packagecom.qdu.sun;importjava.io.IOException;importjava.io.PrintWriter;importjavax.servlet.ServletException;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjavax.servlet.http.HttpSession;importjava.sql.*;publicclassLoginSvltextendsHttpServlet {privateString username;privateString password;publicLoginSvlt() {super();

}publicvoiddestroy() {super.destroy();//Just puts "destroy" string in log//Put your code here}/*** The doGet method of the servlet.

*

* This method is called when a form has its tag value method equals to get.

*

*@paramrequest the request send by the client to the server

*@paramresponse the response send by the server to the client

*@throwsServletException if an error occurred

*@throwsIOException if an error occurred*//*** The doPost method of the servlet.

*

* This method is called when a form has its tag value method equals to post.

*

*@paramrequest the request send by the client to the server

*@paramresponse the response send by the server to the client

*@throwsServletException if an error occurred

*@throwsIOException if an error occurred*/publicvoiddoPost(HttpServletRequest request, HttpServletResponse response)throwsServletException, IOException {

username=request.getParameter("username");

password=request.getParameter("password");//先定义变量,后使用和关闭Connection conn=null;//声明数据库连接对象Statement stmt=null;//声明数据库表达式对象ResultSet rs=null;//声明结果集对象try{//载入Mysql的驱动字符串Class.forName("com.mysql.jdbc.Driver");//获取数据库的连接conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/login","root","123456");//获取表达式对象实例stmt=conn.createStatement();

rs=stmt.executeQuery("select * from user where username='"+username+"'and password='"+password+"'");if(rs.next())

{

HttpSession session=request.getSession(true);

session.setAttribute("username", username);

response.sendRedirect("welcome.jsp");

}else{

response.sendRedirect("error.jsp");

}

}catch(Exception e) {

e.printStackTrace();

}

}/*** Initialization of the servlet.

*

*@throwsServletException if an error occurs*/publicvoidinit()throwsServletException {//Put your code here}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值