如何使用Java和MySQL确定插入或更新是否成功? [英] How do you determine if an insert or update was successful using Java and MySQL?

查看:857
本文介绍了如何使用Java和MySQL确定插入或更新是否成功?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using Java to connect to a MySQL database. I am trying to insert or update data into the database.

即使我非常确定插入成功,它也会返回false。

Even though I am quite sure the insert was successful, it returns false.

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

According to the "execute" API, the return value is "true if the first result is a ResultSet object; false if it is an update count or there are no results".

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

How can I determine whether or not my insert or update was successful?

    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() -

Since you are using PreparedStatement you can call executeUpdate() -

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

从上面的Javadoc(返回)链接,重点添加,

From the Javadoc (Returns) link above, emphasis added,


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

either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements that return nothing.

如果你想插入大量条目,我宁愿< a href =http://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html#addBatch%28%29> addBatch() executeBatch()

If you want to insert a large number of entries, I would prefer addBatch() and executeBatch().

这篇关于如何使用Java和MySQL确定插入或更新是否成功?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆