简体   繁体   中英

how to insert into table using jdbc, when there are compound keys

I have a table with attributes (id, language_id, genre_name) . genre_name gets names in two languages, and id and language_id are part of the primary key. How to make 'insert' new values using JDBC(preparedStatement,(java.sql.Connection) Connection), so, id can be the same for language_id automatically?
For example:

id | language_id| name                    |
1  |      1     | name in one language    |
1  |      2     | name in another language|

PS id is auto-incremented.

Insertion through JDBC is pretty straightforward. You have to connect your database (which you haven't named), then create the PreparedStatement through the data that you need (which means you should have the language_id and name before hand).

This would be a rough example:

String SQL_INSERT = "INSERT INTO genre(language_id, name) VALUES (?, ?)";

try (Connection conn = DriverManager.getConnection(
        "jdbc:postgresql://127.0.0.1:5432/test", "postgres", "password");
     PreparedStatement preparedStatement = conn.prepareStatement(SQL_INSERT)) {

    preparedStatement.setInt(1, YOUR_ID_COMES_HERE);
    preparedStatement.setString(2, YOUR_NAME);

    int row = preparedStatement.executeUpdate();

    // rows affected
    System.out.println(row); //1

} catch (SQLException e) {
    System.err.format("SQL State: %s\n%s", e.getSQLState(), e.getMessage());
} catch (Exception e) {
    e.printStackTrace();
}

This is an example with Postgresql, but if you search on google how to perform insertion with java JDBC, you will have a lot more resources than this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM