JDBC通用更新数据

JDBC_test

public class Jdbc_test {

    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException, NoSuchMethodException, InvocationTargetException, IOException {
        String sql = "insert into emp values(default,?,?)"; //预编译语句
        //更新语句
        update(sql,"admin3",111);
    }

    public static void update(String sql,Object...args) throws SQLException, IOException, ClassNotFoundException {
        //加载配置文件
        Connection conn = JDBCUtils.getConnection();
        //插入语句
        PreparedStatement ps =conn.prepareStatement(sql);
        for(int i=0;i<args.length;i++){
            ps.setObject(i+1,args[i]);
        }
        ps.executeUpdate(); //执行
        JDBCUtils.close(conn,ps);//关闭资源
    }
}

 

JDBCUtils.Class

public class JDBCUtils {
    /**
     * 建立连接
     * @return Connection
     * @throws IOException
     * @throws ClassNotFoundException
     * @throws SQLException
     */
    public static Connection getConnection() throws IOException, ClassNotFoundException, SQLException {
        InputStream is = Jdbc_test.class.getClassLoader().getResourceAsStream("jdbc.propertise");
        Properties properties = new Properties();
        properties.load(is);
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        String url = properties.getProperty("url");
        String driver = properties.getProperty("driver");
        //连接数据库
        Class.forName(driver);
        Connection conn = DriverManager.getConnection(url,user,password);
        return conn;
    }

    /**
     * 关闭资源
     * @param conn
     * @param sm
     * @throws SQLException
     */
    public static void close(Connection conn, Statement sm) throws SQLException {
        if (conn != null){
            conn.close();
        }
        if(sm != null){
            sm.close();
        }

    }
}

 

posted @ 2021-10-26 18:50  白_沙  阅读(109)  评论(0编辑  收藏  举报