使用dbutils封装工具类实现查询操作

1.首先需要用到mysql的jar包mysql-connector-java-8.0.28.jar,具体jar包可以去网上搜索下载。下载完成后把jar包复制到idea软件包的lib目录下(如没有lib目录则自己创建)。复制成功把jar包添加到构建路径。

2.准备一个数据库表。

3.创建DBUtils工具类,获取数据库连接。

import com.mysql.cj.protocol.Resultset;

import java.sql.*;

//获取连接
public class DBUtils {
    public static Connection getConnection()  {
        Connection connection= null;
        try {
            connection = null;
            Class.forName("com.mysql.jdbc.Driver");
            connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","123456");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;



    }
//释放资源
    public static void closeAll(Connection connection, Statement statement,ResultSet resultSet){
        try {
            if (resultSet!=null){
                resultSet.close();
            }
            if (connection!=null){
                connection.close();

            }
            if (statement!=null){
                statement.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}

4.创建LoginJdbc2类实现数据库查询操作,实现登录功能。

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

public class LoginJdbc2 {
    public static void main(String[] args) throws SQLException {
        Scanner scanner=new Scanner(System.in);
        System.out.println("请输入用户名");
        String name = scanner.nextLine();
        System.out.println("请输入密码");
        String password = scanner.nextLine();
        Connection connection=DBUtils.getConnection();
        //获得preparedStatement对象 预编译sql语句
        PreparedStatement preparedStatement = connection.prepareStatement("select *from login where name=? and  password=?;");
        //为?占位符赋值
        preparedStatement.setString(1,name);
        preparedStatement.setString(2,password);
        //执行sql语句,并执行结果
        ResultSet resultSet = preparedStatement.executeQuery();
        if (resultSet.next()){
            System.out.println("登陆成功!");
        }else {
            System.out.println("登陆失败!");
        }
 DBUtils.closeAll(connection,preparedStatement,resultSet);
    }
}

5.运行LoginJdbc2类,实现登录操作

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值