0
可能重複:
Update a record if ID exist else Insert values更新,如果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();
}
%>
例外處理JSP頁/dynatree/dbconnection.jsp在管線26 23:\t 24:\t字符串sqlCheck =「SELECT * FROM [UAP]。[dbo]。[UAP_EMPLOYEE] where EMP_EMPLOYEE_ID ='「+ empId +」'「; 25:\t PreparedStatement prpStatementCheck = conn.prepareStatement(sqlCheck); 26:\t prpStatementCheck.setString(1,empId); 27:\t prpStatementCheck.setString(2,fName); 28:\t prpStatementCheck.setString(3,lName); 29:\t ResultSet rsCheck = prpStatementCheck.executeQuery(); 索引1超出範圍。 – Nash 2012-08-13 00:15:38
此錯誤表明舊語法仍在使用,例如引號EMP_EMPLOYEE_ID,沒有PreparedStmt placeolders,'?'等。 – Reimeus 2012-08-13 01:01:00
即使在按照您的建議更改prpStatement之後也會出現同樣的錯誤。發生
例外處理JSP頁/dynatree/dbconnection.jsp在管線26 23:\t 24:\t字符串sqlCheck =「SELECT * FROM [UAP] [DBO] [UAP_EMPLOYEE]其中EMP_EMPLOYEE_ID =。。 「+ EMPID +」 「; 25:\t PreparedStatement prpStatementCheck = conn.prepareStatement(sqlCheck); 26:\t prpStatementCheck.setInt(1,Integer.parseInt(empId)); 27:\t prpStatementCheck.setString(2,fName); 28:\t prpStatementCheck.setString(3,lName); 29:\t ResultSet rsCheck = prpStatementCheck.executeQuery(); – Nash 2012-08-13 06:33:38