Code example for PreparedStatement

Methods: close, executeUpdate, getGeneratedKeys, setInt, setString

0
			if(rs.getRow() == 0)
			{ 
				//int id = 0; 
				sql = "INSERT INTO food (rest_id, name, description, vote) VALUES (?, ?, ?, 0)";
				stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
				stmt.setInt(1, rest_id);
				stmt.setString(2, name);
				stmt.setString(3, description);
				stmt.executeUpdate();
 
				ResultSet rs1 = stmt.getGeneratedKeys();
				rs1.next();
				if (rs1.getRow() != 0)
				{ 
					//write the pics to server 
					try{ 
					File file = new File("/var/www/lighttpd/picture/" + rs1.getInt(1) + ".jpg");
					FileOutputStream fw = new FileOutputStream(file);
					fw.write(image, 0, image.length);
					fw.close();
					} 
					catch (Exception e)
					{ 
						out.println("Failed");
						return; 
					} 
					//json 
					js.addProperty("result", true);
					js.addProperty("message", "Food has been added");
				} 
				else 
				{ 
					js.addProperty("result", false);
					js.addProperty("message", "Not found");
				} 
			} 
			else 
			{ 
				js.addProperty("result", false);
				js.addProperty("message", "Duplicate found");
			} 
			 
			out.println(js.toString());
			//STEP 6: Clean-up environment 
			stmt.close();
			conn.close();
		}catch(SQLException se){
			//Handle errors for JDBC 
			se.printStackTrace();
		}catch(Exception e){
			//Handle errors for Class.forName 
			e.printStackTrace();
		}finally{ 
			//finally block used to close resources 
			try{ 
				if(stmt!=null)
					stmt.close();
			}catch(SQLException se2){
			}// nothing we can do 
			try{ 
				if(conn!=null)
					conn.close();