如何使用Java和MySQL确定插入或更新是否成功?

我正在使用Java连接到MySQL数据库。 我正在尝试将数据插入或更新到数据库中。

尽管我非常确定插入是成功的,但它返回false。

根据“execute”API,返回值为“如果第一个结果是ResultSet对象,则为true;如果是更新计数,则为false”或“没有结果”。

如何确定插入或更新是否成功?

public boolean insertSelections(String selection, String name){ String sql ="INSERT INTO WORKREPORT VALUES (?,?,?,?,?)"; boolean action = false; try { PreparedStatement stmt = conn.prepareStatement(sql); SimpleDateFormat dateFormat = new java.text.SimpleDateFormat("yyyy:MM:dd hh:mm:ss"); String formatDate = dateFormat.format(new java.util.Date(System.currentTimeMillis())); java.util.Date mDate = dateFormat.parse(formatDate); java.sql.Timestamp timeStamp = new java.sql.Timestamp(System.currentTimeMillis()); // Date time= new Date(mDate.getTime()); stmt.setInt(1, Integer.parseInt(getNumberByName(name).trim())); stmt.setString(2, name); // stmt.setDate(3, time); stmt.setTimestamp(3, timeStamp); stmt.setString(4, selection); stmt.setString(5, "N/A"); action = stmt.execute(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } return action; } 

由于您使用的是PreparedStatement ,因此可以调用executeUpdate()

  int count = stmt.executeUpdate(); action = (count > 0); // <-- something like this. 

从上面的Javadoc( 返回 )链接,重点补充说,

(1) SQL数据操作语言 (DML)语句行计数或(2)0表示不返回任何内容的SQL语句。

如果要插入大量条目,我更喜欢addBatch()executeBatch()

首先,你应该知道:

boolean execute()在此PreparedStatement对象中执行SQL语句,该对象可以是任何类型的SQL语句。

ResultSet executeQuery()在此PreparedStatement对象中执行SQL查询,并返回查询生成的ResultSet对象。

int executeUpdate()执行此PreparedStatement对象中的SQL语句,该语句必须是SQL INSERT,UPDATE或DELETE语句; 或者不返回任何内容的SQL语句,例如DDL语句。

  int i=stmt.executeUpdate(); if(i>0) { System.out.println("success"); } else { System.out.println("stuck somewhere"); } 

试试这个并检查插件是否发生

如果你没有得到例外,我认为查询是好的。 或者,您可以使用executeUpdate()( http://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html#executeUpdate()

您可以执行选择计数(*)如果需要,可以validation记录数。

试试这个,无论你是想知道数据是否插入,如果插入记录,它返回true或者返回false。

  if(action > 0){ return true; }else{ return false; }