import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class JdbcUtils {
private static String url;
private static String user;
private static String password;
static{
try {
Class.forName("com.mysql.jdbc.Driver");
InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties p = new Properties();
p.load(in);
url = p.getProperty("url");
user = p.getProperty("user");
password = p.getProperty("password");
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException{
return DriverManager.getConnection(url, user, password);
}
public static void closeAll(Connection conn, PreparedStatement ps, ResultSet rs){
if (conn !=null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (ps !=null){
try {
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (rs !=null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
实现查询
public class USerDaoImpl implements UserDao{
@Override
public boolean login(UserDamain userDamain) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
String sql="select id from user where username=? and password=?";
ps = conn.prepareStatement(sql);
ps.setString(1,userDamain.getUsername());
ps.setString(2,userDamain.getPassword());
rs = ps.executeQuery();
if (rs.next()) {
return true;
}else{
return false;
}
} catch (Exception e) {
e.printStackTrace();
}finally{
JdbcUtils.closeAll(conn, ps, rs);
}
return false;
}
|