如果数据库中可用ID,则更新,否则插入

时间:2012-08-12 20:35:17

标签: java sql-server-2008 jsp

  

可能重复:
  Update a record if ID exist else Insert values

如果记录存在,我正在尝试更新值,否则将值插入数据库中。但是,这是行不通的。我写了下面的代码:

注意:(主持人,这是我几分钟前问过的重复问题。我无法编辑上一个问题。如果有任何不便,请致歉。请求您删除。)

 <%
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:sqlserver://10.222.10.19:1433", "sa", "admin1");



String empId = request.getParameter("empid");
String fName = request.getParameter("fName");
String lName = request.getParameter("lName");


String sqlCheck = "Select * from [UAP].[dbo].[UAP_EMPLOYEE] where EMP_EMPLOYEE_ID = "empId" ";
PreparedStatement prpStatementCheck = conn.prepareStatement(sqlCheck);
prpStatementCheck.setInt(1, Integer.parseInt(empId));
prpStatementCheck.setString(2, fName);
prpStatementCheck.setString(3, lName);
ResultSet rsCheck=prpStatementCheck.executeQuery();
String check=null;
boolean exists = false;

 while(rsCheck.next())
{

         Statement stmt = conn.createStatement();
         String sql= "UPDATE [UAP].[dbo].[UAP_EMPLOYEE] SET EMP_EMPLOYEE_ID="+empId+", EMP_FNAME='"+fName+"', EMP_LNAME='"+lName+"' WHERE EMP_EMPLOYEE_ID= ?";
         stmt.executeUpdate(sql);
         exists = true;

     }
 if(!exists) 
     {
         String sql2 = "INSERT INTO [UAP].[dbo].[UAP_EMPLOYEE] (EMP_EMPLOYEE_ID, EMP_FNAME, EMP_LNAME ) VALUES (?,?,?)";
            PreparedStatement prpStatement1 = conn.prepareStatement(sql2);
            prpStatement1.setInt(1, Integer.parseInt(empId));

            prpStatement1.setString(2, fName);
            prpStatement1.setString(3, lName);

            prpStatement1.execute();
            prpStatement1.close();   

     }

%GT;

1 个答案:

答案 0 :(得分:1)

由于EMP_EMPLOYEE_ID是INTEGER字段,您需要使用:

prpStatementCheck.setInt(1, Integer.parseInt(empId));

此外,您可以删除此字段周围的引号以获取UPDATE字符串:

String sql= "UPDATE  [UAP_EMPLOYEE] SET EMP_EMPLOYEE_ID=" + empId + ", EMP_FNAME='" + fName+"', EMP_LNAME='" + lName + "' WHERE EMP_EMPLOYEE_ID= " + empId;

再次针对prpStatement1

prpStatement1.setInt(1, Integer.parseInt(empId));