我在更新/插入数据到 SQL 表中时遇到问题。下面的代码扫描数据,然后决定是否更新或插入有关表中找到的任何类似数据值的数据。
但是,即使表中有数据,程序也没有执行 rs.next()
。
public class newInputSQL {
Connection conx;
public newInputSQL(String name, int quantity) {
try {
conx = DriverManager.getConnection("jdbc:derby://localhost:1527/InventoryBase", "Serbesius", "N01094L");
Class.forName("org.apache.derby.jdbc.ClientDriver");
inputGraphin(name, quantity, conx);
} catch (SQLException s) {
System.err.println("SQL error: " + s.toString() + s.getSQLState() + s.getErrorCode());
} catch (ClassNotFoundException cnfe) {
System.err.println("Class not found error: " + cnfe.getMessage());
} finally {
try {
conx.close();
} catch (SQLException ex) {
System.err.println("Error while cleaning resources. Pass me a proper dustpan" + ex.getMessage());
}
}
}
public final void inputGraphin(String name, int quantity, Connection conn) throws SQLException {
String inputName = null;
Statement st = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
System.out.println("Inserting data into resultset...");
ResultSet rs = st.executeQuery("SELECT NAME FROM SERBESIUS.GRAPHINT WHERE NAME ='" + name + "'");
while (rs.next()) {
System.out.println("Scanning");
inputName = rs.getString(1);
//rs.beforeFirst();
}
rs.beforeFirst();
if (inputName == null) {
System.out.println("inserting....");
st.execute("INSERT INTO SERBESIUS.GRAPHINT(NAME, QUANTITY) values('" + name + "', '" + quantity + "')");
} else if (inputName.equals(name)) {
System.out.println("Updating.....");
st.execute("UPDATE SERBESIUS.GRAPHINT SET QUANTITY = '" + quantity + "' WHERE '" + name + "' ");
}
// Clean up resources.....
rs.close();
st.close();
}
}
最佳答案
- 你做的事情比应有的复杂得多。 MySQL已经具备UPSERT/MERGE的功能。
http://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html
- 连接值 = SQL 注入(inject)。
使用准备好的语句。
https://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html
INSERT INTO SERBESIUS.GRAPHINT(NAME, QUANTITY) values(?,?)
on duplicate key update SET QUANTITY = quantity + ?;
附注
期望别人调试你的代码并不严重。
关于java - 更新或插入库存程序的代码。扫描结果集时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40327075/