数据库
首页 > 数据库> > Java之JDBC详谈(数据库)

Java之JDBC详谈(数据库)

作者:互联网

一、了解JDBC

  1. JDBC是什么?
    Java DataBase Connectivity(Java语言连接数据库)
  2. JDBC的本质
    JDBC是SUN公司制定的一套接口(interface)
    java.sql.*(这个软件包下有很多接口)
    开始面向接口编程,面向抽象编程,不要面向具体编程。
  3. JDBC编程六步(需要背会)

二、连接数据库、实现用户登录

2.1前期准备

public class JdbcTest {
    public static void main(String[] args) throws SQLException {
        try {
            //1、注册驱动
            DriverManager.registerDriver(new com.mysql.jdbc.Driver());//这是一种加载驱动方式
            //这是另外一种加载驱动方式,我们从文件中读信息
            FileInputStream file = new FileInputStream("db.properties");
            //创建Map集合对象
            Properties properties = new Properties();
            //将文件信息以键值对的形式加载出来
            properties.load(file);


            //还可以使用一个比较简便的
            ResourceBundle bundle = ResourceBundle.getBundle("文件名");
            String driver = bundle.getString("key");


            //获取文件信息
            String driver = properties.getProperty("driver");
            String url = properties.getProperty("url");
            String username = properties.getProperty("username");
            String password = properties.getProperty("password");
            //通过反射加载驱动
            Class.forName(driver);
            System.out.println(driver);
            //2、获取连接
            Connection connection = DriverManager.getConnection(url, username, password);
            System.out.println(connection);
            //3、获取执行sql的对象
            Statement statement = connection.createStatement();
            String sql = "select * from smbms_role";
            //4、执行sql语句5、返回结果集
            ResultSet resultSet = statement.executeQuery(sql);
            resultSet.next();
            System.out.println(resultSet.getInt("id"));
            //6、释放资源
            resultSet.close();
            statement.close();
            connection.close();
          //关闭资源时,必须从小到大按顺序关闭,并且每个都要try--catch
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
//多写几遍,多查看API文档,了解每个类具体干什么的,你就懂了,也就学会了。

2.2用户登录代码实现

public class LoginTest {
    public static void main(String[] args) {
        //1.获取用户登录信息
        Map<String,String> userInfo = userInfo();
        //2.验证用户密码是否正确
        boolean loginResult = userLogin(userInfo);
        System.out.println(loginResult?"登录成功" : "登录失败");
    }


    //获取用户登录信息
    public static Map<String,String> userInfo() {
        Scanner scan = new Scanner(System.in);
        System.out.println("输入用户名:");
        String username = scan.next();
        System.out.println("输入密码:");
        String password = scan.next();
        HashMap<String, String> user = new HashMap<>();
        user.put("username",username);
        user.put("password",password);
        return user;
    }
    //jdbc
    public static boolean userLogin(Map<String,String> userInfo) {
        boolean falg = false;
        Connection conn = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            String username = userInfo.get("username");
            String password = userInfo.get("password");
            //1.加载驱动
            Class.forName("com.mysql.jdbc.Driver");
            //2.获取连接
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/smbms?useUnicode=true&characterEncoding=utf8&useSSL=false", "root", "200506lx");
            //3.获取操作对象
            statement = conn.createStatement();
            //4.执行sql
            //5.返回结果
            String sql = "select * from smbms_user where userCode = '"+username+"'and userPassword = '"+password+"'";
            resultSet = statement.executeQuery(sql);
            if(resultSet.next()) {
                falg = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 6.释放资源
            if(resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return falg;
    }
}

三、sql注入问题

public static boolean userLogin(Map<String,String> userInfo) {
        boolean falg = false;
        Connection conn = null;
        PreparedStatement ps = null;//将Statement换成PreparedStatement
        ResultSet resultSet = null;
        try {
            String username = userInfo.get("username");
            String password = userInfo.get("password");
            //1.加载驱动
            Class.forName("com.mysql.jdbc.Driver");
            //2.获取连接
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/smbms?useUnicode=true&characterEncoding=utf8&useSSL=false", "root", "200506lx");
            //3.获取操作对象
            //一个?就是一个占位符,接受一个值
            String sql = "select * from smbms_user where userCode = ? and userPassword = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1,username); //1代表第一个?,给他设置值username
            ps.setString(2,password); //JDBC下标从1开始
            //4.执行sql
            //5.返回结果
            resultSet = ps.executeQuery();
            if(resultSet.next()) {
                falg = true;
            }
        }
}

四、对比Statement和PreparedStatement

五、JDBC事务演示

六、JDBC工具类的封装

public class DButil {
    /*
    工具类中的构造方法都是私有的
    因为工具类中的代码都是静态的,不需要new对象,直接采用类名调用
     */
    private DButil(){
    }
    private static final String driver;
    private static final String url;
    private static final String username;
    private static final String password;
    //静态代码块随着类的加载而加载,并且只加载一次
    static {
        ResourceBundle rb = ResourceBundle.getBundle("db.properties");
        driver = rb.getString("driver");
        url = rb.getString("url");
        username = rb.getString("username");
        password = rb.getString("password");
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    //获取数据库的连接
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url,username,password);
    }
    //数据库资源关闭
    public static  void closeResource(Connection conn, PreparedStatement ps, ResultSet rs) {
        if(conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(ps != null) {
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

七、结尾