【发布时间】:2016-10-19 09:03:43
【问题描述】:
我有一个带有 SQL 数据库的 java 应用程序,它使用preparedStatement 将行插入到数据库中。我希望程序能够根据序列号(唯一)更新行。
Connection conn = null;
Statement st = null;
try {
conn = DriverManager.getConnection ("jdbc:derby://localhost:1527/db01", "Administrator", "admin"); //run procedure getConnection to connect to the database - see below
st = conn.createStatement(); //set up a statement st to enable you to send SQL statements to the database.
} catch (SQLException ex) {
Logger.getLogger(FormTwo1.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println ("Successful Connection");
...
String query = "insert into TB01(SERIAL,BLADETYPE,STARTT1,AIRT1,FOAMT1,SCT1,FINISHT1) values (?, ?, ?, ?, ?, ?, ?)";
try (PreparedStatement pstmt = conn.prepareStatement(query)) {
pstmt.setString(1, bladeSerial);
pstmt.setString(2, itemText);
pstmt.setString(3, String.valueOf(startTime1));
pstmt.setString(4, String.valueOf(airTime1));
pstmt.setString(5, String.valueOf(foamTime1));
pstmt.setString(6, String.valueOf(scTime1));
pstmt.setString(7, String.valueOf(finishTime1));
pstmt.executeUpdate();
} catch (SQLException ex) {
// Exception handling
Logger.getLogger(FormTwo1.class.getName()).log(Level.SEVERE, null, ex);
}
其中serial、bladetype 是VARCHAR,startT1、foamTime1、scTime1 和finishTime1 都是LocalTime 变量(因此使用string.valueof 进行格式化)。
数据库是db01,表是TB01
我希望程序根据序列号是否已经在数据库中来插入/更新记录。
【问题讨论】:
-
您的问题是什么?如果要更新行,则需要使用
UPDATE语句,而不是INSERT语句。另外:您使用它的方式,TB01是一个 table 而不是“数据库”。 -
对不起,如果它是唯一序列,我希望代码插入更新,或者如果已经输入,则更新数据库中的一行。你是对的,TB01 是表,DB01 是数据库。
-
在 Derby 中,您可以为此使用
MERGE语句。不相关,但是:您应该永远将数字或日期作为字符串传递。 始终使用适当的数据类型。setInt()用于整数,setDate()用于日期,setTimestamp()用于时间戳等