一、配置文件 (jdbc1.properties)
url 本地数据库地址
user 数据库的账号
password 数据库的密码
driver 注册地址
url=jdbc:mysql://localhost:3306/db1?serverTimezone=GMT%2B8
user=root
password=root
driver=com.mysql.cj.jdbc.Driver
二、工具类
1.成员变量 :用于接收配置文件的四个信息
private static String url;
private static String user;
private static String password;
private static String driver;
2.静态代码块 :注册驱动
//静态代码块 在加载类时候就执行一次
static {
//使用加载配置文件方式
try {
Properties pro = new Properties();
//1读取配置文件绝对地址
pro.load(new FileReader("E:\\Java_IDEA\\project\\src\\cn\\jdbc1.properties"));
//2传入数据
url = pro.getProperty("url");
user = pro.getProperty("user");
password = pro.getProperty("password");
driver = pro.getProperty("driver");
//3注册驱动
Class.forName(driver);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
3.返回连接数据库的对象
public static Connection getconnection() throws SQLException {
return DriverManager.getConnection(url,user,password);
}
4.释放资源
第一个参数:连接数据库的对象
第二个参数:执行sql语句的对象
第三个参数:数据库返回的结果对象
public static void close(Connection conn, Statement state , ResultSet result){
if (result != null){
try {
result.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();
}
}
}
注:在进行多个数据库操作时候需要多次注册驱动,使用工具类 可以简化代码,直接在配置文件里修改信息就可。
三、实现登录
1.msyql数据库的账户表
2.用户方法
true :能在表中找到 输入的账号和密码
false:找不到
public boolean account(String username,String password){
if (username == null || password == null){
return false;
}
Connection conn = null;
PreparedStatement pstate = null;
ResultSet result = null;
try {
//1.注册驱动和连接
conn = Util_demo.getconnection();
//2.使用preparedstatement 执行sql语句
String sql = "select * from account where username = ? and password = ?";
//3.创建执行sql对象
pstate = conn.prepareStatement(sql);
//4.输入数据 第一个参数是?的位置 第二个参数是值
pstate.setString(1,username);
pstate.setString(2,password);
//5.创建数据对象 不需要输入参数
result = pstate.executeQuery();
return result.next();
} catch (SQLException e) {
e.printStackTrace();
}finally {
//pstate 父类引用实现子类对象
Util_demo.close(conn,pstate,result);
}
return false;
}
使用 PreparedStatement 而不是 Statemen :防止 sql 注入(特殊关键字参与字符串的拼接,会造成安全性问题)
3.Main
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入账号:");
String username = sc.nextLine();
System.out.println("请输入密码:");
String password = sc.nextLine();
boolean account = new account_demo().account(username,password);;
if (account){
System.out.println("登陆成功");
}else System.out.println("账号或密码错误");
}
四、结果