java使用原生MySQL实现数据的增删改查

一、工具类及配置文件准备工作

1.1 引入jar包

使用原生MySQL,只需要用到MySQL连接的jar包,maven引用方式如下:

       <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.48</version>
        </dependency>

1.2 jdbc.properties文件配置

在resources文件夹根目录,新增jdbc.properties配置文件,内容如下:

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mydb
user=root
password=123456

1.3 JDBCUtils工具类

在java文件夹中新增 util --> JDBCUtils.java 类,该类中获取jdbc.properties中的值。

JDBCUtils工具类主要作用是简化获取MySQL配置文件、关闭资源。

    private static String url;
    private static String user;
    private static String password;

    static {
        Properties properties = new Properties();
        try {
            properties.load(Mytest.class.getClassLoader().getResourceAsStream("jdbc.properties"));
            url = properties.getProperty("url");
            user = properties.getProperty("user");
            password = properties.getProperty("password");
            Class.forName(properties.getProperty("driver"));
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    // 1.获取jdbc.properties配置文件中的数据库连接
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url, user, password);
    }
    // 5.定义关闭资源的方法
    public static void close(Connection conn, Statement stmt, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {}
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {}
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {}
        }
    }
    public static void close(Connection conn, Statement stmt) {
        close(conn, stmt, null);
    }

二、原生MySQL实现增删改查

2.1 语法说明 

1、通过Connection获取数据库连接对象;

2、定义sql语句(一般可以在Navicat中直接执行);

3、通过获取执行sql的对象 --PreparedStatement;

4、执行sql语句:增删改使用conn的executeUpdate方法(成功返回值为int=1),查询使用executeQuery方法(返回值为ResultSet,建议使用下文的查询方法操作);

5、释放资源(执行SQL时定义的stmt、获取连接时的conn)。

2.2 新增数据 -- insertUser()

在java文件夹中新增MyService.java类,将获取数据库连接抽取出来,方法如下:

    private Connection conn;
    {
        try {
            conn = JDBCUtils.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

在MyService.java类中新增 insertUser方法,具体如下

String sql = "INSERT INTO user values (4, '腾讯科技', 'xinfeng37812', '2009-11-16', '广东省深圳市')";
PreparedStatement  stmt = conn.prepareStatement(sql);
int count = stmt.executeUpdate(sql);
JDBCUtils.close(conn, stmt);
return count;

2.2 修改数据 -- updateById()

String sql = "update user set password = 567875 where id = 2";
PreparedStatement stmt = conn.prepareStatement(sql);
int count = stmt.executeUpdate(sql);
JDBCUtils.close(conn, stmt);
return count;

2.3 删除数据 -- deleteUser()

String sql = "delete from user where id = 5";
PreparedStatement  stmt = conn.prepareStatement(sql);
int count = stmt.executeUpdate(sql);
JDBCUtils.close(conn, stmt);
return count;

2.4 查询数据 -- findAll()

前提:新建 entity --> User.java 实体类,并获取getter&setter、toSting方法;

        String sql = "select * from user";
        PreparedStatement stmt = conn.prepareStatement(sql);
        ResultSet count = stmt.executeQuery(sql);
        User user = null;
        List<User> arr = new ArrayList<>();
        while(count.next()){
            Long id = count.getLong("id");
            String username = count.getString("username");
            String password = count.getString("password");
            Date birthday = count.getDate("birthday");
            String address = count.getString("address");
            user = new User();
            user.setId(id);
            user.setUsername(username);
            user.setPassword(password);
            user.setBirthday(birthday);
            user.setAddress(address);
            arr.add(user);
        }
        JDBCUtils.close(conn, stmt, count);
        return arr;

三、原生MySQL语句的缺点

1、每一次查询都要新增通道,关闭通道,效率太低。实际项目中都会用数据库连接池进行优化;

2、实际项目中使用最多的就是查询,但是将查询的ResultSet结果,进行封装的代码过于臃肿。

猜你喜欢

转载自www.cnblogs.com/fanbao/p/12331827.html
今日推荐