[英]how to insert into table using jdbc, when there are compound keys
I have a table with attributes (id, language_id, genre_name)
.我有一个带有属性
(id, language_id, genre_name)
的表。 genre_name
gets names in two languages, and id
and language_id
are part of the primary key. genre_name
获取两种语言的名称, id
和language_id
是主键的一部分。 How to make 'insert' new values using JDBC(preparedStatement,(java.sql.Connection) Connection), so, id
can be the same for language_id
automatically?如何使用 JDBC(preparedStatement,(java.sql.Connection) Connection)“插入”新值,所以
language_id
ID 的id
可以自动相同?
For example:例如:
id | language_id| name |
1 | 1 | name in one language |
1 | 2 | name in another language|
PS id
is auto-incremented. PS
id
是自动递增的。
Insertion through JDBC is pretty straightforward.通过 JDBC 插入非常简单。 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).您必须连接您的数据库(您尚未命名),然后通过您需要的数据创建
PreparedStatement
(这意味着您应该事先拥有language_id
和name
)。
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.这是 Postgresql 的示例,但是如果您在 google 上搜索如何使用 java JDBC 执行插入,您将拥有比这更多的资源。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.