创建一个工具类,用于连接数据库
package com.dbcon;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class DBConnnection {
public Connection getCon() {
Connection dbCon = null;
try {
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
//获取连接
//数据库连接地址 127.0.0.1代表是本地,1433代表是端口号, BeiJingStud是数据库名
String dbURL = "jdbc:mysql://localhost:3306/BeiJingStud";
String userName = "root"; //用户名
String pwd = "root"; //数据库用户登录密码
dbCon = DriverManager.getConnection(dbURL, userName, pwd);
} catch (Exception e) {
e.printStackTrace();
}
return dbCon;
}
//关闭数据连接和查询信息
public void closeCon(Connection dbCon, Statement stmt, ResultSet rs) {
try{
if (dbCon != null) {
dbCon.close();
}
if (stmt != null) {
stmt.close();
}
if (rs != null) {
rs.close();
}
}catch(Exception e){
e.printStackTrace();
}
}
struts 中的action
package com.exampleLogin;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import com.bean.StudInfoBean;
import com.dbcon.DBConnnection;
import com.mysql.jdbc.PreparedStatement;
public class ExampleLoginAction extends DispatchAction {
public ActionForward loginSuccess(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) {
System.out.println("登录进来了");
//获取登录名和密码 1 通过request的方法获得参数
String name = request.getParameter("textName");
String pwd = request.getParameter("textPwd");
//2 通过form的get方法获得参数
ExampleLoginForm form_ = (ExampleLoginForm) form;
String name1 = form_.getTextName();
String pwd1 = form_.getTextPwd();
//连接数据库
DBConnnection DB = new DBConnnection();
Connection conInfo = DB.getCon();
try {
String sql = "select * from loginuser where LoginName =? and LoginPwd =? ";
PreparedStatement pst = (PreparedStatement) conInfo.prepareStatement(sql);
pst.setString(1, name1);
pst.setString(2, pwd1);
ResultSet rs = pst.executeQuery();
/*try {
Statement stmt = null; //处理模式
ResultSet rs = null; //查询结果集
//得到数据库处理模式
stmt = conInfo.createStatement();
//编写得到所有学生信息
String sql = "select * from loginuser where LoginName ='"+name+"' and LoginPwd ='"+pwd+"' ";
//根据SQL语句查询
rs = stmt.executeQuery(sql);
*/
if(rs.next()){
//关闭资源
DB.closeCon( conInfo, pst, rs);
System.out.println("恭喜,"+name1+"登录成功");
return mapping.findForward("loginsuccess");
}else {
DB.closeCon( conInfo, pst, rs);
System.out.println("对不起登录失败");
return mapping.findForward("loginfail");
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}