详情页

sql技术 --insert 变 update

时间:2024年03月30日

编辑:佚名

应用场景:
mysql 的 t_user 表中有 1000 条数据,这 1000 条数据中有 700 条坏数据 (坏数据指的是 t_user 表中的 logo 字段的值是不正确的)。
需求:找出这些坏数据,使他们变成正确的数据。
处理步骤:
1. 运维将 t_user 表的数据导出来,传给我。
2. 我手动的删除 t_user 表中正确的数据。
3. 在 java 层取出坏数据,循环坏数据,给 logo 字段赋值正确的值。
4. 循环完后,我本地的 mysql 中 t_user 表中的数据就是正确的数据。
问题点
这些数据怎么给运维呢?
我从本地 t_user 表中导出的数据只能是
insert into t_user values(value1,value2,...)
即 insert 语句。
此处有两种解决方案
方案 1: 将我生成的正确数据 与 原来手动删除的正确数据 整合在一起,然后将 t_user 表原封的发给运维。
方案 2: 直接将更新 logo 字段的 sql 发给运维,运维直接执行 sql 语句就行。
总结:方案 1 是将数据发给运维;方案 2 是将 sql 语句发给运维。
我采用的是第二种方案
上述已经说过了,循环完坏数据后,本地 t_user 表中的数据是正确的,但是只能导出 insert into 语句。
因此,只能在执行更新 logo 字段的时候,将 update 语句保存下来。
保存起来的原理是:将 update 字符串写入一个 txt 文件。将字符串写入 txt 文件代码如下
    //写入文件
    public void testFileOutputStream(String sql,File file) throws IOException {
        //1.创建文件对象
        //输出的物理文件可以不存在,执行过程中,
        //若不存在,则会自动创建;若存在,则会将现有文件覆盖
        //File file = new File("sql.txt");
        //2.创建一个文件输出流,用于写入数据到文件中
        FileOutputStream fos = null;
        try {
            //FileOutputStream的第二个参数设置为true,表示写入某个文件的时候,内容不覆盖原来的
            fos = new FileOutputStream(file,true);
            //3.写入数据到文件中
            fos.write(sql.getBytes());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally {
            if (fos != null) {
                //4.关闭输出流
                fos.close();
            }
        }
    }
外层调用写入文件方法
public void test(){
    //1.创建文件对象
    File file = new File("sql.txt");
    //2.取出坏数据  
    select * from t_user;
    //3.循环坏数据  
    for(){
        //4.更新logo字段  
        update t_user set logo=? where id = ?
        //将update字符串写入txt文件  
        String inFileString = "update t_user set logo=? where id = ?"+";"+"\n";
        testFileOutputStream(inFileString,file);
    }
}
最后在工程下面便会生成 sql.txt 文件
相关文章
猜你需要