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

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

Even though I am quite sure the insert was successful, it returns 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;

}

解决方案

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

int count = stmt.executeUpdate();

action = (count > 0); //

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

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值