Java_jdbc 基础笔记之七 数据库连接(方法升级)

 

之前的更新方法

public static void update(String sql) {
        Connection conn = null;
        Statement statement = null;
        try {
            conn = JDBCTools.getConnection();
            statement = conn.createStatement();
            statement.executeUpdate(sql);// attention。。。

        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            JDBCTools.close(statement, conn);
        }

    }
}

 

升级后的方法:

/**
 * 写一个通用的更新方法 包括 INSERT DELETE UODATE 使用工具类
 * 执行SQL语句,使用PreparedStatement
 * 
 * @param sql
 * @param args:填写SQL占位符放入可变参数
 */

 

public static void update(String sql, Object... args) {
        // 可变参数数组
        Connection conn = null;
        PreparedStatement preparedstatement = null;
        try {
            conn = JDBCTools.getConnection();
            preparedstatement = conn.prepareStatement(sql);
            //数组使用for循环,填充占位符!!!
            for (int i = 0; i < args.length; i++) {
                preparedstatement.setObject(i + 1, args[i]);
            }

            preparedstatement.executeUpdate();

        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            JDBCTools.close(preparedstatement, conn);
        }

    }

 

 

 

转: https://blog.csdn.net/YL1214012127/article/details/48293137

 

posted @ 2019-12-11 17:17  与f  阅读(161)  评论(0编辑  收藏  举报