如何通过跳过而不填写其他字段来更新特定数据字段?

时间:2014-09-29 12:23:25

标签: java jdbc

示例是我必须选择

1全部更新

2更新个人

当我输入2时,将显示

[1]更新父亲

[2]更新母亲

[3]更新Brother

[4]更新姐姐

当我选择2(更新母亲)时,我只能更新母数据,

这是我的代码,我有4个扫描仪。更新一切正常,但我无法对数据库进行单独更新。

    int id;
    String father, mother, brother, sister;

    System.out.println("Father ");
    Scanner fath = new Scanner(System.in);
    father = fath.nextLine();

    System.out.println("Mother ");
    Scanner moth = new Scanner(System.in);
    mother = moth.nextLine();

    System.out.println("Brother ");
    Scanner bro = new Scanner(System.in);
    brother = bro.nextLine();

    System.out.println("Sister");
    Scanner sis = new Scanner(System.in);
    sister = sis.nextLine();


    sis.close();
    bro.close();
    fath.close();
    moth.close();

PreparedStatement ps = con
                        .prepareStatement("Update family set father = ?, mother = ?, brother = ?, sister = ? where id =?");
            ps.setString(1, father);
            ps.setString(2, mother);
            ps.setString(3, brother);
            ps.setString(4, sister);
            ps.setInt(5, id);
            ps.executeUpdate();

2 个答案:

答案 0 :(得分:0)

它取决于数据库中表的结构。这些列是否可以为空,或者确切地说是对这些列应用了哪种约束。

此外,如果这些列在表中可以为空,那么您可以使用只有一个?的更新查询,并传递要插入的值并执行相同的值。

例如,

con.prepareStatement("Update family set father = ? where id =?");
ps.setString(1, father);
ps.setInt(2, id);
ps.executeUpdate();

以上查询只会更新father表中的family列。

答案 1 :(得分:0)

PreparedStatement ps = con.prepareStatement(" Update family set father = ?,其中id =?");             ps.setString(1,father);             ps.setInt(2,id);             ps.executeUpdate();