- 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
{
//1.加载驱动
Class.forName(jdbc_driver);
//2.链接数据库
connection = DriverManager.getConnection(url, root, password);//2.
}catch (ClassNotFoundException|SQLException e){
System.out.println("数据库连接失败,请查看配置");
e.printStackTrace();
}
if(connection==null){
System.out.println("数据库连接失败,请查看配置");
}
return connection;
}
//3.释放资源
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 = ?";//sql语句
ResultSet rs ;//结果集
PreparedStatement pstmt = conn.prepareStatement(sql);//4.预编译
pstmt.setString(1,name);//为地址为1的?赋值
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";
}



