- DButils代码实现
package com.nly.webPro.Utils;
import java.sql.*;
import static com.nly.webPro.Utils.Constant.*;
public class DButils {
public static Connection getConnection() throws ClassNotFoundException, SQLException {
Connection connection = null;
try
{
Class.forName(jdbc_driver);
connection = DriverManager.getConnection(url, root, password);
}catch (ClassNotFoundException|SQLException e){
System.out.println("数据库连接失败,请查看配置");
e.printStackTrace();
}
if(connection==null){
System.out.println("数据库连接失败,请查看配置");
}
return connection;
}
public static void close(Connection conn, PreparedStatement pstmt){
try{
if(pstmt!=null){
pstmt.close();
}
if(conn!=null){
conn.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
2.登录功能的实现(Dao层代码)
public class loginDao {
public boolean loginIn(String name,String password) throws SQLException, ClassNotFoundException {
Connection conn = DButils.getConnection();
String sql = "select * from users where username = ? and password = ?";
ResultSet rs ;
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1,name);
pstmt.setString(2,password);
rs = pstmt.executeQuery();
System.out.println(rs);
if(rs.next()){
DButils.close(conn,pstmt);
return true;
}else{
DButils.close(conn,pstmt);
return false;}
}
}
3.连接数据库常量设置
public class Constant {
public static String USER_SESSION = "USER_SESSION";
public static String root = "root";
public static String password = "123456";
public static String url = "jdbc:mysql://localhost:3306/users?useSSL=false&useUnicode=true&characterEncoding=UTF-8";
public static String jdbc_driver = "com.mysql.jdbc.Driver";
}
|