我有关于将数据更新/插入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();
}
}
答案 0 :(得分:1)
http://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html
https://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html
INSERT INTO SERBESIUS.GRAPHINT(NAME, QUANTITY) values(?,?)
on duplicate key update SET QUANTITY = quantity + ?;
P.S。
期望其他人调试您的代码并不严重。
答案 1 :(得分:1)
你太复杂了。检查行是否已经存在的查询没有必要 - 无论如何更新都会这样做。只需运行更新,检查是否有任何行已被修改,如果没有进行插入。
您还应永远将值连接到SQL语句中。请改用PreparedStatement
。
public final void inputGraphin(String name, int quantity, Connection conn) throws SQLException {
PreparedStatement update = conn.createStatement("INSERT INTO SERBESIUS.GRAPHINT(NAME, QUANTITY) values (?,?)");
PreparedStatement insert = conn.createStatement("UPDATE SERBESIUS.GRAPHINT SET QUANTITY = ? where name = ?");
update.setString(1, name);
update.setInt(1, quantity);
int rowsUpdated = update.executeUpdate();
if (rowsUpdated <= 0) {
insert.setInt(1, quantity);
insret.setSting(2, name);
insert.executeUpdate();
}
// !!!
// the cleanup should be in a finally block
update.close();
insert.close();
}
不相关,但是:现代JDBC驱动程序不再需要Class.forName()
。 Java 5中引入的服务注册表将负责这一点。
但是,如果您确实认为自己需要它,那么必须先使用 调用DriverManager.getConnection()
。
但在您的情况下,您只需删除对Class.forName()