Database Manipulation operations in apex

Database Manipulation operations – insert, update, upsert, delete, undelete & merge:




Below are the different database manipulation languages in apex.

insert: This keyword is used to insert one or more records. See the below example to understand how can we use this in apex code.




Example:
Lead l = new Lead(Company=’ABC’,LastName=’Rahul’);
insert l;

update: This keyword is used to update/modifications to the existing records. See the below example to understand how can we use this in apex code.
Example:
Account a = new Account(Name=’MyAcc1′);
insert a;
Account myAcct = [SELECT Id, Name, BillingCity FROM Account WHERE Name = ‘MyAcc1’ LIMIT 1];
myAcct.BillingCity = ‘Melbourne’;
try {
update myAcct;
} catch (DmlException e) {
}

upsert: This keyword is used to creates/insert new records and updates existing records. See the below example to understand how can we use this in apex code.
Example:
Account[] acctsList = [SELECT Id, Name, BillingCity FROM Account WHERE BillingCity = ‘Bombay’];
for (Account a : acctsList)
{a.BillingCity = ‘Mumbai’;}
Account newAcct = new Account(Name = ‘Ramco’, BillingCity = ‘Hyderabad’);
acctsList.add(newAcct);
try {
upsert acctsList;
}
catch (DmlException e) {
}

delete: This key word is used to delete the records.
Example:
Account[] delAccts = [SELECT Id, Name FROM Account WHERE Name = ‘domnos’];
try {
delete delAccts;
} catch (DmlException e) {
// Process exception here
}

undelete: This keyword is used to restore the records from the recyclebin.
Example:
Account[] accts = [SELECT Id, Name FROM Account WHERE Name = ‘myAcc’ ALL ROWS];
try {
undelete accts;
}
catch (DmlException e) {
}

Merge: This keyword merges up to three records of the same type into one of the records, deleting the others, and re-parenting any related records.
Example:
List<Account> accList = new List<Account>{new Account(Name=’Myacc1′),new Account(Name=’MyAcc2′)};
insert accList;
Account masterAcct = [SELECT Id, Name FROM Account WHERE Name = ‘Myacc1’ LIMIT 1];
Account mergeAcct = [SELECT Id, Name FROM Account WHERE Name = ‘MyAcc2’ LIMIT 1];
try {
merge masterAcct mergeAcct;
}
catch (DmlException e) {
}





if, else, do, while, for, break, continue

if, else, do, while, for, break, continue – Key words




if: This keyword defines a condition, used to determine whether a code block should be executed.
Example:
Integer i = 1;
if (i > 0) {
// do something;
}

else: Defines the else portion of an if-else statement, that executes if the initial evaluation is untrue.
Example:
Integer x, sign;
if (x==0) {
sign = 0;
} else {
sign = 1;
}

while: This keyword executes a block of code repeatedly as long as a particular Boolean condition remains true.
Example:
Integer count=1;
while (count < 11) {
System.debug(count);
count++;
}

do: This keyword defines a do-while loop that executes repeatedly while a Boolean condition remains true.
Example:
Integer count = 1;
do {
System.debug(count);
count++;
}

for: This keyword Defines a loop. The three types of for loops are: iteration using a variable, iteration over a list, and iteration over a query.
Example:
for (Integer i = 0, j = 0; i < 10;
i++) { System.debug(i+1);
}
Integer[] myInts = new Integer[]{1,8, 9};
for (Integer i : myInts) {
System.debug(i);
}
String s = ‘Acme’;
for (Account a : [SELECT Id, Name,FROM account
WHERE Name LIKE :(s+’%’)]) {
// Your code
}

break: This keyword Exits the entire loop.
Example:
while(reader.hasNext()) {
if (reader.getEventType() == END) {
break;
};
// process
reader.next();
}

continue: This keyword Skips to the next iteration of the loop.
Example:
while (checkBoolean) {
if (condition)
{continue; }
// do some work
}








try, catch, finally, throw keywords

Exceptional Handling -try, catch, finally, throw keywords




Exception occurs during the execution of a program. We have to handle the excretion in code.  Like java, apex has exception handling mechanism. Below are the Keywords(try, catch, finally, throw keywords) related to Exceptional Handling




try: This keyword is used to identifies a block of code in which an exception can occur.
Example:
try {
// Your code here
} catch (ListException e) {
// List Exception handling code
// here
}

catch: This keyword is used to identifies a block of code that can handle a particular type of exception.
Example:
try {
// Your code here
} catch (ListException e) {
// List Exception handling code here
}




finally: This keyword is used to identifies a block of code that is guaranteed to execute.
Example:
try {
// Your code here
} catch (ListException e) {
// List Exception handling code
} finally {
// will execute with or without
// exception
}

throw: This keyword is used to throws an exception, signaling that an error has occurred.
Example:
public class MyException extends
Exception {}
try {
Integer i;
if (i < 5)
throw new MyException();
} catch (MyException e) {
// Your MyException handling
// code here
}








Static, Final, this, super keywords in apex

Important keywords in Apex




Below are the some important keywords in apex programming language.

static: This keyword defines a method/variable that is only initialized once, and is associated with an (outer) class, and initialization code. We can call static variables/methods by class name directly. No need of creating instance of a class.
Example:
public class OuterClass {
// Associated with instance
public static final Integer MY_INT;
// Initialization code
static {
MY_INT = 10;
}
}

final: This keyword is used to Defines constants and methods that can’t be overridden.
Example:
public class myCls {
static final Integer INT_CONST;
}



this: This keyword represents the current instance of a class , in constructor chaining.
Example:
public class Foo {
public Foo(String s) { /* … */}
public foo() {
this(‘memes repeat’); }
}

super: This keyword invokes a constructor on a superclass.
Example:
public class AnotherChildClass extends InnerClass {
AnotherChildClass(String s) {
super();
// different constructor, no
// args
}
}



return: This keyword returns a value from a method.
Example:
public Integer sum() {
return int_var;
}

transient: This keyword declares instance variables that cannot be saved, and should not be transmitted as part of the view state, in Visualforce controllers and extensions.
Example:
transient integer currentValue;

null: This keyword defines a null constant that can be assigned to any variable.
Example:
Boolean b = null;

Like other programming languages there are many other keywords in Apex programming language. We will see those in other posts.





public,private,protected & global keywords in Apex Programming

Access specifier keywords used in Apex Programming




We can also call public, private, protected & global as access modifiers. Apex allows these 4 types of modifiers.

1. public: This keyword is used to Defines a class or method or variable that can be used by any Apex in this application or namespace.




Example:
public class Foo {
public void quiteVisible();
private void almostInvisible();
}

2. private: This key word is used to Defines a class/method/variable that is only known locally, within the section of code in which it is defined. This is the default scope for all methods and variables that do not have a scope defined.
Example:
public class OuterClass {
private static final Integer MY_INT;
}

3. protected: This keyword defines a method/variable that is visible to any inner classes in the defining Apex class.
Example:
public class Foo {
public void quiteVisible();
protected void lessVisible();
}

4.global: Defines a class, method, or variable that can be used by any Apex that has access to the class, not just the Apex in the same application.
Example:
global class myClass {
webService static void
makeContact(String lastName) {
// do some work
}

See reference to understand more about apex programming access modifiers.





With sharing & Without sharing keywords.

With sharing & Without sharing keywords




With sharing Keyword: This keyword enforces sharing rules that apply to the current user. If absent, code is run under default system context.




Example:
public with sharing class MysharingClass {
// Code will enforce current user’s
// sharing rules
}

Without sharing keyword: Ensures that the sharing rules of the current user are not enforced.
Example:
public without sharing class noSharing {
// Code won’t enforce current user’s
// sharing rules
}





Class, Abstract, Implements, extends, interface keywords in Apex

Apex Reserved keywords




1. Class: This keyword is used to define a class.
Example:
private class MyClass {
private Integer number;
public Integer getNumber()
{
return number;
}
}

2. Abstract: This keyword is used to define abstract classes. An abstract class that contains methods only have signature and no body defined. Can also defined methods.
Example:
public abstract class MyAbstrtactClass {
protected void myMethod1()
{
/*… */
}
abstract Integer myAbstractMethod1();
}

3. Implements: This keyword is used declare a class that impediments an interface.
Example:
global class CreateTaskEmailExample implements Messaging.InboundEmailHandler {
global Messaging.InboundEmailResulthandleInboundEmail(Messaging.inboundEmail email,Messaging.InboundEnvelope env){
// do some work, return value;
}
}

4. extends: Defines a class that extents another class.
Example:
public class MyClass1 extends MyClass {
}

5. interface: This keyword is used to define a data type with method signatures. Classes implement interfaces. An interface can extend another interface.
Example:
public interface PO {
public void doWork();
}
public class MyPO implements PO {
public override doWork() {
// actual implementation
}
}




6. virtual: This keyword Defines a class or method that allows extension and overrides. You can’t override a method with the override keyword unless the class or method has been defined as virtual.
Example:
public virtual class MyException extends Exception {
// Exception class member
// variable
public Double d;
// Exception class constructor
MyException(Double d) {
this.d = d;
}
// Exception class method
protected void doIt() {}
}








Keywords used in Primitive-Collection Types

Primitive Type Keyword




Below are the primitive data type keywords used in apex langue to declare variables.

1. Blob – This data type represents binary data stored as a single object.




Example: Blob b1 = Blob.valueof(‘idea’);

2. Boolean – This data type represents Value that can only be assigned true, false, or null.
Example: Boolean isvar = true;

3. Date – This data type represents particular day.
Example: Date myDateVar = Date.today();
Date weekStart = myDateVar.toStartofWeek();

4. Datetime – This data type represents particular time and date.
Example: Datetime myDateTimeVar = Datetime.now();
Datetime newd = myDateTimeVar. addMonths(5);

5. Decimal – This data type represents Number that includes a decimal
point. Decimal is an arbitrary precision number.
Example:Decimal myVar = 12.4567;
Decimal divDecVar = myVar.divide(7, 2, System.RoundingMode.UP);
system.assertEquals(divDecVar,1.78);

6. Double – Represents 64-bit number that includes a decimal point. Minimum value -2^63. Maximum value of 2^63-1.
Example:Double d=3.14159;

7. ID – Represents 18-character Force.com record identifier.
Example:ID id=’00300000003T2PGAA0′;

8. Integer – 32-bit number that doesn’t include a decimal point. Minimum value
-2,147,483,648 — maximum value of 2,147,483,647
Example: Integer i = 1;

9. Long – Represents 64-bit number that doesn’t include a decimal point. minimum value of -263 — maximum value of 263-1.
Example:Long l = 2147483648L;

10. String – Represents Set of characters surrounded by single quotes.
Example:String s1 = ‘Hello’;

11. Time – Represents particular time.
Example: Time myTimeVar = Time.newInstance(18, 30, 2, 20);
Integer myMinutes = myTimeVar.
minute();




List Type Keywords:

Below are the Collection Type keyword used in Apex:

1.List – Ordered collection of typed primitives, sObjects, objects, or collections that are distinguished by their indices.
Example:
// Create an empty list of String
List<String> my_list = new List<String>();
My_list.add(‘first’);
String x = my_list.get(0);
// Create list of records from a query
List<Account> accs = [SELECT Id, Name FROM Account LIMIT 1000];

2. Map – Collection of key-value pairs where each unique key maps to a single value. Keys can be any primitive data type, while values can be a primitive, sObject,
collection type, or an object.
Example:
Map<String, String> mys = new Map<String,String>();
Map<String, String> mys = new Map<String,
String>{‘a’ => ‘b’, ‘c’ => ‘d’.toUpperCase()};
Account myAcct = new Account();
Map<Integer, Account> m = new
Map<Integer, Account>();
m.put(1, myAcct);

3. Set – Unordered collection that doesn’t contain any duplicate elements.
Example:
Set<Integer> s = new Set<Integer>();
s.add(1);
s.add(1);
System.assert(s.size()==1);