[英]How to insert data into specific fields of mysql table from the first row in Java
I have a table called Cast with these fields : Id, CastName, CastImdbId
. 我有一个名为Cast的表,其中包含以下
fields : Id, CastName, CastImdbId
。 This table already has many records. 该表已经有很多记录。 Now, I would like to add 3 new fields to this table which are
(gender, castBirthDate, castBirthPlace)
. 现在,我想向该表添加3个新字段,分别是
(gender, castBirthDate, castBirthPlace)
。 The problem is that "insert into"
add new data to the end of table (after the last record), but I need to add these data starting from the first record. 问题是
"insert into"
将新数据添加到表末尾(最后一条记录之后),但是我需要从第一条记录开始添加这些数据。 Could someone please let me know if it is possible and how? 有人可以让我知道是否可行以及如何进行?
This is part of my code which has the problem: 这是我的代码中存在问题的一部分:
try{
String query = "INSERT into Cast (gender, castBirthDate, castBirthPlace)" + "VALUES (?, ?, ?)";
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setString (1, gender);
preparedStmt.setString (2, dateOfBirth);
preparedStmt.setString (3, placeOfBirth);
preparedStmt.executeUpdate();
}catch (Exception e){
System.err.println("Got an exception!");
System.err.println(e.getMessage());
}
Use an ALTER
statement on the table. 在表上使用
ALTER
语句。
Example 例
ALTER TABLE Cast
ADD (gender varchar2(1), //Depending on "F" or "Female"
castBirthDate Date,
castBirthPlace varchar2(50));
Then UPDATE
the new fields. 然后
UPDATE
新字段。 Which can be done in many ways. 这可以通过很多方式来完成。 Avoid the
INSERT
. 避免
INSERT
。
UPDATE
in jdbc
is like this: jdbc
UPDATE
是这样的:
StringBuilder sql = new StringBuilder("");
sql.append("UPDATE Cast ");
sql.append("SET gender = ?, ");
sql.append("castBirthDate = ?, ");
sql.append("castBirthPlace = ? ");
sql.append("WHERE actor_id = ?"); //Assuming...
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setString (1, gender);
preparedStmt.setString (2, dateOfBirth);
preparedStmt.setString (3, placeOfBirth);
preparedStmt.executeUpdate();
Do you want to set those fields values to the existing records? 您是否要将这些字段值设置为现有记录? Then you might want to
UPDATE
them. 然后,您可能想要
UPDATE
它们。
As the name implies, an INSERT
statement will add new rows at the end of the table. 顾名思义,
INSERT
语句将在表的末尾添加新行。
UPDATE
will modify the row or rows you specify, changing the values on the fields you specify. UPDATE
将修改您指定的一个或多个行,从而更改您指定的字段上的值。
UPDATE table SET column1='value1', column4='value2' WHERE column2='thisValue'
In your case, let's say you want to set 'Female' to "Halle Berry" 就您而言,假设您要将“女性”设置为“哈勒·贝瑞”
UPDATE Cast SET gender='Female' WHERE CastName='Halle Berry'
You should of course use IDs and references like F
for 'female' and not the whole word. 当然,您应该使用ID和引用(例如
F
来表示“女性”,而不是整个单词。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.