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();
        }

    }
}

 

上一篇:JDBC连接方式和基本步骤,你愿意看必有收获篇(一)(手写千字,有不足望指出)


下一篇:爬虫操作第三节-保存数据