我想一次在数据库中插入单个数据,但在数据库中一次生成重复行。
-----------------------------
Output(in mysql table=privilege)
-----------------------------
id privilege
1 abc
2 abc
以下是我插入数据的方法:
public int addPrivilege(String privilege) {
PreparedStatement preparedStatement = null;
String sqlprivilege;
Connection dbConnection = null;
int pinsert = 0;
try {
sqlprivilege = "insert into privilege(privilege) values(?)";
dbConnection = ConnectionDao.getDBConnection();
preparedStatement = dbConnection.prepareStatement(sqlprivilege);
preparedStatement.setString(1, privilege);
pinsert = preparedStatement.executeUpdate();
if(preparedStatement.executeUpdate()==1)
pinsert=1;
else
pinsert=0;
System.out.println("privilege is add and name is:- " +privilege);
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dbConnection != null) {
try {
dbConnection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return pinsert;
}
答案 0 :(得分:2)
在代码中执行两次sql。
1) pinsert = preparedStatement.executeUpdate();
2) if(preparedStatement.executeUpdate()==1)
我不确定executeUpdate的返回值。但我认为第一个就足够了,不需要检查返回值。如果你需要再与pinsert进行比较而不是executeupdate(再次)。
if(pinsert == 1)
答案 1 :(得分:0)
你正在使用两次executeUpdate();如果
,删除执行哪一个 public int addPrivilege(String privilege) {
PreparedStatement preparedStatement = null;
String sqlprivilege;
Connection dbConnection = null;
int pinsert = 0;
try {
sqlprivilege = "insert into privilege(privilege) values(?)";
dbConnection = ConnectionDao.getDBConnection();
preparedStatement = dbConnection.prepareStatement(sqlprivilege);
preparedStatement.setString(1, privilege);
pinsert = preparedStatement.executeUpdate();
//try this
if(pinsert ==1)
pinsert=1;
else
pinsert=0;
System.out.println("privilege is add and name is:- " +privilege);
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dbConnection != null) {
try {
dbConnection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return pinsert;
}