0

我正在编写一个程序,它将接收学生 ID 并验证该 ID 是否存在于 mysql 表中。如果它确实存在,我想取出它存在的整行并将该行复制到另一个表中。目前,该程序只会将表中的所有行复制到另一个表中。任何帮助表示赞赏。我在下面插入了一段代码。

try {
    String compareText = IDField.getText().trim();

    if(compareText.length() > 0){
        Class.forName("com.mysql.jdbc.Driver");
        conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/simlab","root","password");
        System.out.println("Connected to database");

        Statement stmt1     = conn.createStatement();
        ResultSet rs1       = stmt1.executeQuery("select * from students where LUID='"+IDField.getText()+"' ");

        boolean isPresent = rs1.next();

        if (isPresent)
        {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/simlab","root","password");
            System.out.println("Connected to database");

            int rows = stmt1.executeUpdate("INSERT INTO skills(ID_Student,LUID_Student)SELECT ID, LUID FROM students");

            if (rows == 0) 
            {
                System.out.println("Don't add any row!");
            } 
            else 
            {
               System.out.println(rows + " row(s)affected.");
               conn.close();
            }

            //System.out.println("Already exists!!");
        }
4

3 回答 3

1

你都可以在一条 SQL 语句中做到这一点:

INSERT INTO <Dest-Table>
(SELECT * FROM <Src-Table> WHERE ID=?);

它只会复制存在的行。

于 2013-03-23T19:07:44.743 回答
0

我怀疑这是由于这条线:

int rows = stmt1.executeUpdate("INSERT INTO skills(ID_Student,LUID_Student)SELECT ID, LUID FROM students");

因为,如果解析了该行,则该SELECT语句没有WHERE子句,因此将获取每一行,因此插入所有内容。

于 2013-03-23T18:56:27.030 回答
0

使用准备好的语句

        String sql = "INSERT INTO abc"
                + "(SELECT id1,id2 FROM pqr)";

        ps1 = con.prepareStatement(sql);


        int rs = ps1.executeUpdate();

        if (rs > 0) {

            update = true;

        } else {
            update = false;
        }

    } catch (Exception ex) {

        ex.printStackTrace();
    } finally {
        try {
            if (ps1 != null) {
                ps1.close();
                ps1 = null;
            }
            if (con != null) {
                con.close();
                con = null;
            }
        } catch (Exception e) {

        }
    }
    return update;
于 2018-01-29T04:19:31.023 回答