可能重复:
如果 ID 存在则更新记录,否则插入值
如果记录存在,我正在尝试更新值,否则将值插入数据库中。但是,这是行不通的。我写了下面的代码:
注意:(版主,这是我几分钟前提出的重复问题。我无法编辑以前的问题。如有任何不便,请致歉。请求您删除。)
<%
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();
}
%>