JDBCUtils
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class JDBCUtils {
private static String driver;
private static String url;
private static String username;
private static String password;
//静态代码块,得到配置文件里面的常量(driver,url,username,passwrd)
static{
InputStream is=null;
try{
is= JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties=new Properties();
properties.load(is);
driver=properties.getProperty("driver");
url=properties.getProperty("url");
username=properties.getProperty("username");
password=properties.getProperty("password");
System.out.println(driver);
System.out.println(url);
System.out.println(username);
System.out.println(password);
}catch (IOException e){
throw new RuntimeException(e);
} finally {
//关闭流
if (is!=null){
try {
is.close();
}catch (IOException e){
throw new RuntimeException(e);
}
}
}
}
public static Connection getConnection() throws SQLException,ClassNotFoundException{
//第一步:加载驱动
Class.forName(driver);
//第二步:创建连接
Connection connection= DriverManager.getConnection(url,username,password);
return connection;
}
//释放资源
public static void close(ResultSet resultSet, Statement statement, Connection connection)throws SQLException{
if (resultSet!=null){
resultSet.close();
}
if (statement!=null){
statement.close();
}
if (connection!=null){
connection.close();
}
}
}
登录代码
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
public class yunxing {
public static void main(String[] args) throws SQLException,ClassNotFoundException{
Scanner scanner=new Scanner(System.in);
System.out.println("用户名:");
String username=scanner.next();
System.out.println("密码:");
String password=scanner.next();
//判断用户名和密码是否在数据库中存在,存在返回登录成功。不存在返回登录失败
String find_username_password_sql="select * from user where username='"+username+"'and password='"+password+"'";
Connection connection= JDBCUtils.getConnection();
Statement statement=connection.createStatement();
ResultSet resultSet=statement.executeQuery(find_username_password_sql);
if (resultSet.next()){
System.out.println("登录成功");
}else{
System.out.println("登录失败");
}
JDBCUtils.close(resultSet,statement,connection);
}
}