Java实现登录账号操作
1.配置文件
在src文件下创建jdbc.properties,其中的内容为
url=jdbc:mysql://localhost:3306/stu
user=root
password=123456
drive=com.mysql.jdbc.Driver
2.JDBCUtils中的内容
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.Properties;
//JDBC工具类
public class JDBCUtils {
private static String url;
private static String password;
private static String user;
private static String drive;
static {
try{
ClassLoader CL = JDBCUtils.class.getClassLoader();
URL res = CL.getResource("jdbc.properties");
String path= res.getPath();
Properties pro=new Properties();
pro.load(new FileReader(path));
url=pro.getProperty("url");
user=pro.getProperty("user");
password=pro.getProperty("password");
drive=pro.getProperty("drive");
Class.forName(drive);
}catch (IOException e){
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
Connection conn= DriverManager.getConnection(url,user,password);
return conn;
}
public static void close(Statement state, Connection conn){
if (state!=null){
try {
state.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(Statement state, Connection conn, ResultSet re){
if (re!=null){
try {
re.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (state!=null){
try {
state.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
3.实现登录的内容
import cn.itcast.utils.JDBCUtils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
public class denglu {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("请输入账号");
String user = sc.nextLine();
System.out.println("请输入密码");
String password=sc.nextLine();
boolean login = new denglu().login(user, password);
if (login==true){
System.out.println("登录成功");
}else {
System.out.println("登录失败");
}
}
public boolean login(String username,String password){
Connection conn=null;
Statement state=null;
ResultSet re=null;
if (username==null||password==null){
return false;
}
try {
conn= JDBCUtils.getConnection();
String sql="select * from user where name='"+username+"'and passwor='"+password+"'";
state = conn.createStatement();
re = state.executeQuery(sql);
return re.next();
} catch (SQLException e) {
e.printStackTrace();
}finally {
JDBCUtils.close(state,conn,re);
}
return false;
}
}