代码实现
package com.lems.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DBUtil {
/**
* 连接数据库的操作,用户名,密码,使用jdbc连接
*/
public static String username = "root";
public static String password = "root";
public static String url = "jdbc:mysql://localhost:3306/test?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
static{
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch(ClassNotFoundException e){
e.printStackTrace();
}
}
public static Connection getConnectDb(){
Connection conn = null;
try{
conn = DriverManager.getConnection(url,username,password);
} catch (SQLException e){
e.printStackTrace();
}
return conn;
}
public static void CloseDB(ResultSet rs, PreparedStatement stm, Connection conn){
if(rs!=null)
{
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(stm!=null)
{
try {
stm.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(conn!=null)
{
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
调用
//登陆
public boolean Login_verify(String username,String password,String role){
Connection conn = DBUtil.getConnectDb();
String sql = "select * from user where username='"+username+"' and password='"+password+"' and role='"+role+"'";
PreparedStatement stm = null;
ResultSet rs = null;
try {
stm = conn.prepareStatement(sql);
rs = stm.executeQuery();
if(rs.next()){
return true;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
DBUtil.CloseDB(rs, stm, conn);
}
return false;
}