在java登陆判断中dao类该如何写?

2024-12-07 12:00:59
推荐回答(2个)
回答1:

你好,dao层统一写,具体的业务写在service层中。因为你还可能有判断登录,注册,他们的实现是不一样的。下面给出一个dao的例子:
package org.fit.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.fit.ex.SysException;

public class Dao {

private static final String DRIVER=
"com.mysql.jdbc.Driver";

private static final String URL=
"jdbc:mysql://localhost:3306/cateweb";

private static final String USER="root";

private static final String PASSWORD="0";

public Dao() throws SysException{
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
e.printStackTrace();
throw new SysException("驱动没有找到!") ;
}
}

private Connection conn;
private PreparedStatement pt;
private ResultSet rs;

public ResultSet query(String sql,Object... paramValues)
throws SQLException{

try {
conn=DriverManager.getConnection(URL,USER,PASSWORD);
pt=conn.prepareStatement(sql);
if(paramValues!=null){
for(int i=0;i pt.setObject(i+1, paramValues[i]);
}
}
rs=pt.executeQuery();
return rs;
} catch (SQLException e) {
e.printStackTrace();
this.close();
throw e;
}

}

public int update(String sql,Object... paramValues)
throws SQLException{
try{
conn=DriverManager.getConnection(URL,USER,PASSWORD);
pt=conn.prepareStatement(sql);
if(paramValues!=null){
for(int i=0;i pt.setObject(i+1, paramValues[i]);
}
}

return pt.executeUpdate();
}finally{
this.close();
}

}

public void close(){
try {
if(rs!=null){
rs.close();
}
} catch (Exception e) {}
rs=null;

try {
if(pt!=null){
pt.close();
}
} catch (Exception e) {}
pt=null;

try {
if(conn!=null){
if(!conn.isClosed())conn.close();
}
} catch (Exception e) {}
conn=null;
}
}

回答2:

用传入的用户名密码在数据库进行查询 SELECT * FROM TABLE_NAME WHERE USERNAME = NAME AND PASSWORD = WORD;大致的SQL语句就是这样的,,你自己看情况修改一下,然后判断如果查询出数据,则说明用户名密码正确,,否则有一项是错误的,这种查询方法是最简单的