1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

  2. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[SQL] Insert a row in a table with referencing to a value from other table

Discussão em 'Outras Linguagens' iniciado por Stack, Julho 28, 2021.

  1. Stack

    Stack Membro Participativo

    I have 2 tables, subject and student respectively

    id | name
    ----+-----------------------------
    1 | Math

    id | student_name | score | subject_id
    ----+--------------+-------+------------
    11 | Mark | 78.5 | 2


    I have the Java code

    public boolean insertStudent(String student_name,float score,String name) {
    boolean res=false;
    try(PreparedStatement statement=this.c.prepareStatement(INSERT_STU);){
    statement.setString(1,student_name);
    statement.setFloat(2,score);
    statement.setString(3,name);
    res=statement.execute();

    }catch (SQLException e){
    e.printStackTrace();
    throw new RuntimeException(e);
    }
    return res;
    }


    I have the query string for INSERT_STU

    private static final String INSERT_STU="INSERT INTO student(student_name,score,subject_id) VALUES(?,?,(SELECT id from subject where name=?))";


    This works in postgres. But is there any other way to do it? *It has to be passed with subject name (String name) and not subject id. Since I won't be knowing the subject_id, I pass the name.

    Continue reading...

Compartilhe esta Página