Changed frappe.conn to frappe.db
diff --git a/erpnext/accounts/Print Format/SalesInvoice/SalesInvoice.html b/erpnext/accounts/Print Format/SalesInvoice/SalesInvoice.html
index 874d84c..d4a49ef 100644
--- a/erpnext/accounts/Print Format/SalesInvoice/SalesInvoice.html
+++ b/erpnext/accounts/Print Format/SalesInvoice/SalesInvoice.html
@@ -1,5 +1,5 @@
 {%- if doc.letter_head -%}
-	{{ frappe.conn.get_value("Letter Head", doc.letter_head, "content") }}
+	{{ frappe.db.get_value("Letter Head", doc.letter_head, "content") }}
 {%- endif -%}
 <!-- Page Layout Settings -->
 <div class='common page-header'>
diff --git a/erpnext/accounts/doctype/account/account.py b/erpnext/accounts/doctype/account/account.py
index dcb12c1..2b7a0b1 100644
--- a/erpnext/accounts/doctype/account/account.py
+++ b/erpnext/accounts/doctype/account/account.py
@@ -7,7 +7,7 @@
 from frappe.utils import flt, fmt_money, cstr, cint
 from frappe import msgprint, throw, _
 
-get_value = frappe.conn.get_value
+get_value = frappe.db.get_value
 
 class DocType:
 	def __init__(self,d,dl):
@@ -16,11 +16,11 @@
 
 	def autoname(self):
 		self.doc.name = self.doc.account_name.strip() + ' - ' + \
-			frappe.conn.get_value("Company", self.doc.company, "abbr")
+			frappe.db.get_value("Company", self.doc.company, "abbr")
 
 	def get_address(self):
 		return {
-			'address': frappe.conn.get_value(self.doc.master_type, 
+			'address': frappe.db.get_value(self.doc.master_type, 
 				self.doc.master_name, "address")
 		}
 		
@@ -41,14 +41,14 @@
 		if self.doc.master_type in ('Customer', 'Supplier') or self.doc.account_type == "Warehouse":
 			if not self.doc.master_name:
 				msgprint(_("Please enter Master Name once the account is created."))
-			elif not frappe.conn.exists(self.doc.master_type or self.doc.account_type, 
+			elif not frappe.db.exists(self.doc.master_type or self.doc.account_type, 
 					self.doc.master_name):
 				throw(_("Invalid Master Name"))
 			
 	def validate_parent(self):
 		"""Fetch Parent Details and validation for account not to be created under ledger"""
 		if self.doc.parent_account:
-			par = frappe.conn.sql("""select name, group_or_ledger, is_pl_account, debit_or_credit 
+			par = frappe.db.sql("""select name, group_or_ledger, is_pl_account, debit_or_credit 
 				from tabAccount where name =%s""", self.doc.parent_account)
 			if not par:
 				throw(_("Parent account does not exists"))
@@ -72,15 +72,15 @@
 
 	def validate_max_root_accounts(self):
 		"""Raise exception if there are more than 4 root accounts"""
-		if frappe.conn.sql("""select count(*) from tabAccount where
+		if frappe.db.sql("""select count(*) from tabAccount where
 			company=%s and ifnull(parent_account,'')='' and docstatus != 2""",
 			self.doc.company)[0][0] > 4:
 			throw(_("One company cannot have more than 4 root Accounts"))
 	
 	def validate_duplicate_account(self):
 		if self.doc.fields.get('__islocal') or not self.doc.name:
-			company_abbr = frappe.conn.get_value("Company", self.doc.company, "abbr")
-			if frappe.conn.sql("""select name from tabAccount where name=%s""", 
+			company_abbr = frappe.db.get_value("Company", self.doc.company, "abbr")
+			if frappe.db.sql("""select name from tabAccount where name=%s""", 
 				(self.doc.account_name + " - " + company_abbr)):
 					throw("{name}: {acc_name} {exist}, {rename}".format(**{
 						"name": _("Account Name"),
@@ -91,14 +91,14 @@
 				
 	def validate_root_details(self):
 		#does not exists parent
-		if frappe.conn.exists("Account", self.doc.name):
-			if not frappe.conn.get_value("Account", self.doc.name, "parent_account"):
+		if frappe.db.exists("Account", self.doc.name):
+			if not frappe.db.get_value("Account", self.doc.name, "parent_account"):
 				throw(_("Root cannot be edited."))
 				
 	def validate_frozen_accounts_modifier(self):
-		old_value = frappe.conn.get_value("Account", self.doc.name, "freeze_account")
+		old_value = frappe.db.get_value("Account", self.doc.name, "freeze_account")
 		if old_value and old_value != self.doc.freeze_account:
-			frozen_accounts_modifier = frappe.conn.get_value( 'Accounts Settings', None, 
+			frozen_accounts_modifier = frappe.db.get_value( 'Accounts Settings', None, 
 				'frozen_accounts_modifier')
 			if not frozen_accounts_modifier or \
 				frozen_accounts_modifier not in frappe.user.get_roles():
@@ -131,10 +131,10 @@
 
 	# Check if any previous balance exists
 	def check_gle_exists(self):
-		return frappe.conn.get_value("GL Entry", {"account": self.doc.name})
+		return frappe.db.get_value("GL Entry", {"account": self.doc.name})
 
 	def check_if_child_exists(self):
-		return frappe.conn.sql("""select name from `tabAccount` where parent_account = %s 
+		return frappe.db.sql("""select name from `tabAccount` where parent_account = %s 
 			and docstatus != 2""", self.doc.name)
 	
 	def validate_mandatory(self):
@@ -148,7 +148,7 @@
 			return
 			
 		if self.doc.account_type == "Warehouse":
-			old_warehouse = cstr(frappe.conn.get_value("Account", self.doc.name, "master_name"))
+			old_warehouse = cstr(frappe.db.get_value("Account", self.doc.name, "master_name"))
 			if old_warehouse != cstr(self.doc.master_name):
 				if old_warehouse:
 					self.validate_warehouse(old_warehouse)
@@ -158,7 +158,7 @@
 					throw(_("Master Name is mandatory if account type is Warehouse"))
 		
 	def validate_warehouse(self, warehouse):
-		if frappe.conn.get_value("Stock Ledger Entry", {"warehouse": warehouse}):
+		if frappe.db.get_value("Stock Ledger Entry", {"warehouse": warehouse}):
 			throw(_("Stock transactions exist against warehouse ") + warehouse + 
 				_(" .You can not assign / modify / remove Master Name"))
 
@@ -174,7 +174,7 @@
 
 	def get_authorized_user(self):
 		# Check logged-in user is authorized
-		if frappe.conn.get_value('Accounts Settings', None, 'credit_controller') \
+		if frappe.db.get_value('Accounts Settings', None, 'credit_controller') \
 				in frappe.user.get_roles():
 			return 1
 			
@@ -182,11 +182,11 @@
 		# Get credit limit
 		credit_limit_from = 'Customer'
 
-		cr_limit = frappe.conn.sql("""select t1.credit_limit from tabCustomer t1, `tabAccount` t2 
+		cr_limit = frappe.db.sql("""select t1.credit_limit from tabCustomer t1, `tabAccount` t2 
 			where t2.name=%s and t1.name = t2.master_name""", self.doc.name)
 		credit_limit = cr_limit and flt(cr_limit[0][0]) or 0
 		if not credit_limit:
-			credit_limit = frappe.conn.get_value('Company', self.doc.company, 'credit_limit')
+			credit_limit = frappe.db.get_value('Company', self.doc.company, 'credit_limit')
 			credit_limit_from = 'Company'
 		
 		# If outstanding greater than credit limit and not authorized person raise exception
@@ -219,10 +219,10 @@
 		
 		# Validate properties before merging
 		if merge:
-			if not frappe.conn.exists("Account", new):
+			if not frappe.db.exists("Account", new):
 				throw(_("Account ") + new +_(" does not exists"))
 				
-			val = list(frappe.conn.get_value("Account", new_account, 
+			val = list(frappe.db.get_value("Account", new_account, 
 				["group_or_ledger", "debit_or_credit", "is_pl_account", "company"]))
 			
 			if val != [self.doc.group_or_ledger, self.doc.debit_or_credit, self.doc.is_pl_account, self.doc.company]:
@@ -234,7 +234,7 @@
 
 	def after_rename(self, old, new, merge=False):
 		if not merge:
-			frappe.conn.set_value("Account", new, "account_name", 
+			frappe.db.set_value("Account", new, "account_name", 
 				" - ".join(new.split(" - ")[:-1]))
 		else:
 			from frappe.utils.nestedset import rebuild_tree
@@ -243,13 +243,13 @@
 def get_master_name(doctype, txt, searchfield, start, page_len, filters):
 	conditions = (" and company='%s'"% filters["company"]) if doctype == "Warehouse" else ""
 		
-	return frappe.conn.sql("""select name from `tab%s` where %s like %s %s
+	return frappe.db.sql("""select name from `tab%s` where %s like %s %s
 		order by name limit %s, %s""" %
 		(filters["master_type"], searchfield, "%s", conditions, "%s", "%s"), 
 		("%%%s%%" % txt, start, page_len), as_list=1)
 		
 def get_parent_account(doctype, txt, searchfield, start, page_len, filters):
-	return frappe.conn.sql("""select name from tabAccount 
+	return frappe.db.sql("""select name from tabAccount 
 		where group_or_ledger = 'Group' and docstatus != 2 and company = %s
 		and %s like %s order by name limit %s, %s""" % 
 		("%s", searchfield, "%s", "%s", "%s"), 
diff --git a/erpnext/accounts/doctype/accounts_settings/accounts_settings.py b/erpnext/accounts/doctype/accounts_settings/accounts_settings.py
index ae4aa55..3e01eea 100644
--- a/erpnext/accounts/doctype/accounts_settings/accounts_settings.py
+++ b/erpnext/accounts/doctype/accounts_settings/accounts_settings.py
@@ -13,15 +13,15 @@
 		self.doc, self.doclist = d, dl
 
 	def on_update(self):
-		frappe.conn.set_default("auto_accounting_for_stock", self.doc.auto_accounting_for_stock)
+		frappe.db.set_default("auto_accounting_for_stock", self.doc.auto_accounting_for_stock)
 		
 		if cint(self.doc.auto_accounting_for_stock):
 			# set default perpetual account in company
-			for company in frappe.conn.sql("select name from tabCompany"):
+			for company in frappe.db.sql("select name from tabCompany"):
 				frappe.bean("Company", company[0]).save()
 			
 			# Create account head for warehouses
-			warehouse_list = frappe.conn.sql("select name, company from tabWarehouse", as_dict=1)
+			warehouse_list = frappe.db.sql("select name, company from tabWarehouse", as_dict=1)
 			warehouse_with_no_company = [d.name for d in warehouse_list if not d.company]
 			if warehouse_with_no_company:
 				frappe.throw(_("Company is missing in following warehouses") + ": \n" + 
diff --git a/erpnext/accounts/doctype/bank_reconciliation/bank_reconciliation.py b/erpnext/accounts/doctype/bank_reconciliation/bank_reconciliation.py
index aa91e5c..859c9d0 100644
--- a/erpnext/accounts/doctype/bank_reconciliation/bank_reconciliation.py
+++ b/erpnext/accounts/doctype/bank_reconciliation/bank_reconciliation.py
@@ -22,7 +22,7 @@
 			msgprint("Bank Account, From Date and To Date are Mandatory")
 			return
 	
-		dl = frappe.conn.sql("select t1.name, t1.cheque_no, t1.cheque_date, t2.debit, t2.credit, t1.posting_date, t2.against_account from `tabJournal Voucher` t1, `tabJournal Voucher Detail` t2 where t2.parent = t1.name and t2.account = %s and (clearance_date is null or clearance_date = '0000-00-00' or clearance_date = '') and t1.posting_date >= %s and t1.posting_date <= %s and t1.docstatus=1", (self.doc.bank_account, self.doc.from_date, self.doc.to_date))
+		dl = frappe.db.sql("select t1.name, t1.cheque_no, t1.cheque_date, t2.debit, t2.credit, t1.posting_date, t2.against_account from `tabJournal Voucher` t1, `tabJournal Voucher Detail` t2 where t2.parent = t1.name and t2.account = %s and (clearance_date is null or clearance_date = '0000-00-00' or clearance_date = '') and t1.posting_date >= %s and t1.posting_date <= %s and t1.docstatus=1", (self.doc.bank_account, self.doc.from_date, self.doc.to_date))
 		
 		self.doclist = self.doc.clear_table(self.doclist, 'entries')
 		self.doc.total_amount = 0.0
@@ -46,7 +46,7 @@
 					msgprint("Clearance Date can not be before Cheque Date (Row #%s)" % 
 						d.idx, raise_exception=1)
 					
-				frappe.conn.sql("""update `tabJournal Voucher` 
+				frappe.db.sql("""update `tabJournal Voucher` 
 					set clearance_date = %s, modified = %s where name=%s""",
 					(d.clearance_date, nowdate(), d.voucher_id))
 				vouchers.append(d.voucher_id)
diff --git a/erpnext/accounts/doctype/c_form/c_form.py b/erpnext/accounts/doctype/c_form/c_form.py
index b60f303..fdf8b30 100644
--- a/erpnext/accounts/doctype/c_form/c_form.py
+++ b/erpnext/accounts/doctype/c_form/c_form.py
@@ -16,7 +16,7 @@
 
 		for d in getlist(self.doclist, 'invoice_details'):
 			if d.invoice_no:
-				inv = frappe.conn.sql("""select c_form_applicable, c_form_no from
+				inv = frappe.db.sql("""select c_form_applicable, c_form_no from
 					`tabSales Invoice` where name = %s and docstatus = 1""", d.invoice_no)
 				
 				if not inv:
@@ -42,17 +42,17 @@
 		
 	def before_cancel(self):
 		# remove cform reference
-		frappe.conn.sql("""update `tabSales Invoice` set c_form_no=null
+		frappe.db.sql("""update `tabSales Invoice` set c_form_no=null
 			where c_form_no=%s""", self.doc.name)
 		
 	def set_cform_in_sales_invoices(self):
 		inv = [d.invoice_no for d in getlist(self.doclist, 'invoice_details')]
 		if inv:
-			frappe.conn.sql("""update `tabSales Invoice` set c_form_no=%s, modified=%s 
+			frappe.db.sql("""update `tabSales Invoice` set c_form_no=%s, modified=%s 
 				where name in (%s)""" % ('%s', '%s', ', '.join(['%s'] * len(inv))), 
 				tuple([self.doc.name, self.doc.modified] + inv))
 				
-			frappe.conn.sql("""update `tabSales Invoice` set c_form_no = null, modified = %s 
+			frappe.db.sql("""update `tabSales Invoice` set c_form_no = null, modified = %s 
 				where name not in (%s) and ifnull(c_form_no, '') = %s""" % 
 				('%s', ', '.join(['%s']*len(inv)), '%s'),
 				tuple([self.doc.modified] + inv + [self.doc.name]))
@@ -61,12 +61,12 @@
 
 	def set_total_invoiced_amount(self):
 		total = sum([flt(d.grand_total) for d in getlist(self.doclist, 'invoice_details')])
-		frappe.conn.set(self.doc, 'total_invoiced_amount', total)
+		frappe.db.set(self.doc, 'total_invoiced_amount', total)
 
 	def get_invoice_details(self, invoice_no):
 		"""	Pull details from invoices for referrence """
 
-		inv = frappe.conn.sql("""select posting_date, territory, net_total, grand_total 
+		inv = frappe.db.sql("""select posting_date, territory, net_total, grand_total 
 			from `tabSales Invoice` where name = %s""", invoice_no)	
 		return {
 			'invoice_date' : inv and getdate(inv[0][0]).strftime('%Y-%m-%d') or '',
@@ -79,7 +79,7 @@
 	from erpnext.utilities import build_filter_conditions
 	conditions, filter_values = build_filter_conditions(filters)
 	
-	return frappe.conn.sql("""select name from `tabSales Invoice` where docstatus = 1 
+	return frappe.db.sql("""select name from `tabSales Invoice` where docstatus = 1 
 		and c_form_applicable = 'Yes' and ifnull(c_form_no, '') = '' %s 
 		and %s like %s order by name limit %s, %s""" % 
 		(conditions, searchfield, "%s", "%s", "%s"), 
diff --git a/erpnext/accounts/doctype/cost_center/cost_center.py b/erpnext/accounts/doctype/cost_center/cost_center.py
index 6665039..e02496f 100644
--- a/erpnext/accounts/doctype/cost_center/cost_center.py
+++ b/erpnext/accounts/doctype/cost_center/cost_center.py
@@ -14,7 +14,7 @@
 		self.nsm_parent_field = 'parent_cost_center'
 				
 	def autoname(self):
-		company_abbr = frappe.conn.sql("select abbr from tabCompany where name=%s", 
+		company_abbr = frappe.db.sql("select abbr from tabCompany where name=%s", 
 			self.doc.company)[0][0]
 		self.doc.name = self.doc.cost_center_name.strip() + ' - ' + company_abbr
 		
@@ -46,10 +46,10 @@
 			return 1
 
 	def check_gle_exists(self):
-		return frappe.conn.get_value("GL Entry", {"cost_center": self.doc.name})
+		return frappe.db.get_value("GL Entry", {"cost_center": self.doc.name})
 		
 	def check_if_child_exists(self):
-		return frappe.conn.sql("select name from `tabCost Center` where \
+		return frappe.db.sql("select name from `tabCost Center` where \
 			parent_cost_center = %s and docstatus != 2", self.doc.name)
 
 	def validate_budget_details(self):
@@ -67,7 +67,7 @@
 		"""
 			Cost Center name must be unique
 		"""
-		if (self.doc.fields.get("__islocal") or not self.doc.name) and frappe.conn.sql("select name from `tabCost Center` where cost_center_name = %s and company=%s", (self.doc.cost_center_name, self.doc.company)):
+		if (self.doc.fields.get("__islocal") or not self.doc.name) and frappe.db.sql("select name from `tabCost Center` where cost_center_name = %s and company=%s", (self.doc.cost_center_name, self.doc.company)):
 			msgprint("Cost Center Name already exists, please rename", raise_exception=1)
 			
 		self.validate_mandatory()
@@ -85,7 +85,7 @@
 		
 	def after_rename(self, olddn, newdn, merge=False):
 		if not merge:
-			frappe.conn.set_value("Cost Center", newdn, "cost_center_name", 
+			frappe.db.set_value("Cost Center", newdn, "cost_center_name", 
 				" - ".join(newdn.split(" - ")[:-1]))
 		else:
 			super(DocType, self).after_rename(olddn, newdn, merge)
diff --git a/erpnext/accounts/doctype/fiscal_year/fiscal_year.py b/erpnext/accounts/doctype/fiscal_year/fiscal_year.py
index 381acf3..3918751 100644
--- a/erpnext/accounts/doctype/fiscal_year/fiscal_year.py
+++ b/erpnext/accounts/doctype/fiscal_year/fiscal_year.py
@@ -11,7 +11,7 @@
 		self.doc, self.doclist = d, dl
 		
 	def set_as_default(self):
-		frappe.conn.set_value("Global Defaults", None, "current_fiscal_year", self.doc.name)
+		frappe.db.set_value("Global Defaults", None, "current_fiscal_year", self.doc.name)
 		frappe.get_obj("Global Defaults").on_update()
 		
 		# clear cache
@@ -21,7 +21,7 @@
 			Please refresh your browser for the change to take effect."""))
 
 	def validate(self):
-		year_start_end_dates = frappe.conn.sql("""select year_start_date, year_end_date 
+		year_start_end_dates = frappe.db.sql("""select year_start_date, year_end_date 
 			from `tabFiscal Year` where name=%s""", (self.doc.name))
 
 		if year_start_end_dates:
@@ -36,7 +36,7 @@
 		if (getdate(self.doc.year_end_date) - getdate(self.doc.year_start_date)).days > 366:
 			frappe.throw(_("Year Start Date and Year End Date are not within Fiscal Year."))
 
-		year_start_end_dates = frappe.conn.sql("""select name, year_start_date, year_end_date 
+		year_start_end_dates = frappe.db.sql("""select name, year_start_date, year_end_date 
 			from `tabFiscal Year` where name!=%s""", (self.doc.name))
 
 		for fiscal_year, ysd, yed in year_start_end_dates:
diff --git a/erpnext/accounts/doctype/gl_entry/gl_entry.py b/erpnext/accounts/doctype/gl_entry/gl_entry.py
index e3eff9b..cbe94fd 100644
--- a/erpnext/accounts/doctype/gl_entry/gl_entry.py
+++ b/erpnext/accounts/doctype/gl_entry/gl_entry.py
@@ -42,7 +42,7 @@
 				self.doc.account)
 			
 	def pl_must_have_cost_center(self):
-		if frappe.conn.get_value("Account", self.doc.account, "is_pl_account") == "Yes":
+		if frappe.db.get_value("Account", self.doc.account, "is_pl_account") == "Yes":
 			if not self.doc.cost_center and self.doc.voucher_type != 'Period Closing Voucher':
 				frappe.throw(_("Cost Center must be specified for PL Account: ") + 
 					self.doc.account)
@@ -55,13 +55,13 @@
 
 	def check_pl_account(self):
 		if self.doc.is_opening=='Yes' and \
-				frappe.conn.get_value("Account", self.doc.account, "is_pl_account") == "Yes":
+				frappe.db.get_value("Account", self.doc.account, "is_pl_account") == "Yes":
 			frappe.throw(_("For opening balance entry account can not be a PL account"))			
 
 	def validate_account_details(self, adv_adj):
 		"""Account must be ledger, active and not freezed"""
 		
-		ret = frappe.conn.sql("""select group_or_ledger, docstatus, company 
+		ret = frappe.db.sql("""select group_or_ledger, docstatus, company 
 			from tabAccount where name=%s""", self.doc.account, as_dict=1)[0]
 		
 		if ret.group_or_ledger=='Group':
@@ -80,7 +80,7 @@
 		
 		def _get_cost_center_company():
 			if not self.cost_center_company.get(self.doc.cost_center):
-				self.cost_center_company[self.doc.cost_center] = frappe.conn.get_value(
+				self.cost_center_company[self.doc.cost_center] = frappe.db.get_value(
 					"Cost Center", self.doc.cost_center, "company")
 			
 			return self.cost_center_company[self.doc.cost_center]
@@ -91,10 +91,10 @@
 						
 def check_negative_balance(account, adv_adj=False):
 	if not adv_adj and account:
-		account_details = frappe.conn.get_value("Account", account, 
+		account_details = frappe.db.get_value("Account", account, 
 				["allow_negative_balance", "debit_or_credit"], as_dict=True)
 		if not account_details["allow_negative_balance"]:
-			balance = frappe.conn.sql("""select sum(debit) - sum(credit) from `tabGL Entry` 
+			balance = frappe.db.sql("""select sum(debit) - sum(credit) from `tabGL Entry` 
 				where account = %s""", account)
 			balance = account_details["debit_or_credit"] == "Debit" and \
 				flt(balance[0][0]) or -1*flt(balance[0][0])
@@ -108,9 +108,9 @@
 		except authorized person
 	"""
 	if not adv_adj:
-		acc_frozen_upto = frappe.conn.get_value('Accounts Settings', None, 'acc_frozen_upto')
+		acc_frozen_upto = frappe.db.get_value('Accounts Settings', None, 'acc_frozen_upto')
 		if acc_frozen_upto:
-			bde_auth_role = frappe.conn.get_value( 'Accounts Settings', None,'bde_auth_role')
+			bde_auth_role = frappe.db.get_value( 'Accounts Settings', None,'bde_auth_role')
 			if getdate(posting_date) <= getdate(acc_frozen_upto) \
 					and not bde_auth_role in frappe.user.get_roles():
 				frappe.throw(_("You are not authorized to do/modify back dated entries before ")
@@ -118,7 +118,7 @@
 
 def update_outstanding_amt(account, against_voucher_type, against_voucher, on_cancel=False):
 	# get final outstanding amt
-	bal = flt(frappe.conn.sql("""select sum(ifnull(debit, 0)) - sum(ifnull(credit, 0)) 
+	bal = flt(frappe.db.sql("""select sum(ifnull(debit, 0)) - sum(ifnull(credit, 0)) 
 		from `tabGL Entry` 
 		where against_voucher_type=%s and against_voucher=%s and account = %s""", 
 		(against_voucher_type, against_voucher, account))[0][0] or 0.0)
@@ -126,7 +126,7 @@
 	if against_voucher_type == 'Purchase Invoice':
 		bal = -bal
 	elif against_voucher_type == "Journal Voucher":
-		against_voucher_amount = flt(frappe.conn.sql("""
+		against_voucher_amount = flt(frappe.db.sql("""
 			select sum(ifnull(debit, 0)) - sum(ifnull(credit, 0))
 			from `tabGL Entry` where voucher_type = 'Journal Voucher' and voucher_no = %s
 			and account = %s and ifnull(against_voucher, '') = ''""", 
@@ -143,13 +143,13 @@
 		
 	# Update outstanding amt on against voucher
 	if against_voucher_type in ["Sales Invoice", "Purchase Invoice"]:
-		frappe.conn.sql("update `tab%s` set outstanding_amount=%s where name='%s'" %
+		frappe.db.sql("update `tab%s` set outstanding_amount=%s where name='%s'" %
 		 	(against_voucher_type, bal, against_voucher))
 			
 def validate_frozen_account(account, adv_adj=None):
-	frozen_account = frappe.conn.get_value("Account", account, "freeze_account")
+	frozen_account = frappe.db.get_value("Account", account, "freeze_account")
 	if frozen_account == 'Yes' and not adv_adj:
-		frozen_accounts_modifier = frappe.conn.get_value( 'Accounts Settings', None, 
+		frozen_accounts_modifier = frappe.db.get_value( 'Accounts Settings', None, 
 			'frozen_accounts_modifier')
 		
 		if not frozen_accounts_modifier:
diff --git a/erpnext/accounts/doctype/journal_voucher/journal_voucher.py b/erpnext/accounts/doctype/journal_voucher/journal_voucher.py
index f02188b..c1635bd 100644
--- a/erpnext/accounts/doctype/journal_voucher/journal_voucher.py
+++ b/erpnext/accounts/doctype/journal_voucher/journal_voucher.py
@@ -75,7 +75,7 @@
 		for d in getlist(self.doclist,'entries'):
 			if not d.is_advance and not d.against_voucher and \
 					not d.against_invoice and not d.against_jv:
-				master_type = frappe.conn.get_value("Account", d.account, "master_type")
+				master_type = frappe.db.get_value("Account", d.account, "master_type")
 				if (master_type == 'Customer' and flt(d.credit) > 0) or \
 						(master_type == 'Supplier' and flt(d.debit) > 0):
 					msgprint("Message: Please check Is Advance as 'Yes' against \
@@ -87,7 +87,7 @@
 				if d.against_jv == self.doc.name:
 					msgprint("You can not enter current voucher in 'Against JV' column",
 						raise_exception=1)
-				elif not frappe.conn.sql("""select name from `tabJournal Voucher Detail` 
+				elif not frappe.db.sql("""select name from `tabJournal Voucher Detail` 
 						where account = '%s' and docstatus = 1 and parent = '%s'""" % 
 						(d.account, d.against_jv)):
 					msgprint("Against JV: %s is not valid." % d.against_jv, raise_exception=1)
@@ -125,12 +125,12 @@
 		
 		for d in getlist(self.doclist, 'entries'):
 			if d.against_invoice and d.credit:
-				currency = frappe.conn.get_value("Sales Invoice", d.against_invoice, "currency")
+				currency = frappe.db.get_value("Sales Invoice", d.against_invoice, "currency")
 				r.append('%s %s against Invoice: %s' % 
 					(cstr(currency), fmt_money(flt(d.credit)), d.against_invoice))
 					
 			if d.against_voucher and d.debit:
-				bill_no = frappe.conn.sql("""select bill_no, bill_date, currency 
+				bill_no = frappe.db.sql("""select bill_no, bill_date, currency 
 					from `tabPurchase Invoice` where name=%s""", d.against_voucher)
 				if bill_no and bill_no[0][0] and bill_no[0][0].lower().strip() \
 						not in ['na', 'not applicable', 'none']:
@@ -153,7 +153,7 @@
 			# check account type whether supplier or customer
 			exists = False
 			for d in getlist(self.doclist, 'entries'):
-				account_type = frappe.conn.get_value("Account", d.account, "account_type")
+				account_type = frappe.db.get_value("Account", d.account, "account_type")
 				if account_type in ["Supplier", "Customer"]:
 					exists = True
 					break
@@ -166,12 +166,12 @@
 
 	def set_print_format_fields(self):
 		for d in getlist(self.doclist, 'entries'):
-			account_type, master_type = frappe.conn.get_value("Account", d.account, 
+			account_type, master_type = frappe.db.get_value("Account", d.account, 
 				["account_type", "master_type"])
 				
 			if master_type in ['Supplier', 'Customer']:
 				if not self.doc.pay_to_recd_from:
-					self.doc.pay_to_recd_from = frappe.conn.get_value(master_type, 
+					self.doc.pay_to_recd_from = frappe.db.get_value(master_type, 
 						' - '.join(d.account.split(' - ')[:-1]), 
 						master_type == 'Customer' and 'customer_name' or 'supplier_name')
 			
@@ -190,7 +190,7 @@
 		if date_diff <= 0: return
 		
 		# Get List of Customer Account
-		acc_list = filter(lambda d: frappe.conn.get_value("Account", d.account, 
+		acc_list = filter(lambda d: frappe.db.get_value("Account", d.account, 
 		 	"master_type")=='Customer', getlist(self.doclist,'entries'))
 		
 		for d in acc_list:
@@ -202,11 +202,11 @@
 					
 	def get_credit_days_for(self, ac):
 		if not self.credit_days_for.has_key(ac):
-			self.credit_days_for[ac] = cint(frappe.conn.get_value("Account", ac, "credit_days"))
+			self.credit_days_for[ac] = cint(frappe.db.get_value("Account", ac, "credit_days"))
 
 		if not self.credit_days_for[ac]:
 			if self.credit_days_global==-1:
-				self.credit_days_global = cint(frappe.conn.get_value("Company", 
+				self.credit_days_global = cint(frappe.db.get_value("Company", 
 					self.doc.company, "credit_days"))
 					
 			return self.credit_days_global
@@ -218,7 +218,7 @@
 			self.is_approving_authority = 0
 
 			# Fetch credit controller role
-			approving_authority = frappe.conn.get_value("Global Defaults", None, 
+			approving_authority = frappe.db.get_value("Global Defaults", None, 
 				"credit_controller")
 			
 			# Check logged-in user is authorized
@@ -229,12 +229,12 @@
 
 	def check_account_against_entries(self):
 		for d in self.doclist.get({"parentfield": "entries"}):
-			if d.against_invoice and frappe.conn.get_value("Sales Invoice", 
+			if d.against_invoice and frappe.db.get_value("Sales Invoice", 
 					d.against_invoice, "debit_to") != d.account:
 				frappe.throw(_("Row #") + cstr(d.idx) +  ": " +
 					_("Account is not matching with Debit To account of Sales Invoice"))
 			
-			if d.against_voucher and frappe.conn.get_value("Purchase Invoice", 
+			if d.against_voucher and frappe.db.get_value("Purchase Invoice", 
 					d.against_voucher, "credit_to") != d.account:
 				frappe.throw(_("Row #") + cstr(d.idx) + ": " +
 					_("Account is not matching with Credit To account of Purchase Invoice"))
@@ -267,7 +267,7 @@
 			
 	def check_credit_limit(self):
 		for d in self.doclist.get({"parentfield": "entries"}):
-			master_type, master_name = frappe.conn.get_value("Account", d.account, 
+			master_type, master_name = frappe.db.get_value("Account", d.account, 
 				["master_type", "master_name"])
 			if master_type == "Customer" and master_name:
 				super(DocType, self).check_credit_limit(d.account)
@@ -328,18 +328,18 @@
 		cond = (flt(self.doc.write_off_amount) > 0) and \
 			' and outstanding_amount <= '+ self.doc.write_off_amount or ''
 		if self.doc.write_off_based_on == 'Accounts Receivable':
-			return frappe.conn.sql("""select name, debit_to, outstanding_amount 
+			return frappe.db.sql("""select name, debit_to, outstanding_amount 
 				from `tabSales Invoice` where docstatus = 1 and company = %s 
 				and outstanding_amount > 0 %s""" % ('%s', cond), self.doc.company)
 		elif self.doc.write_off_based_on == 'Accounts Payable':
-			return frappe.conn.sql("""select name, credit_to, outstanding_amount 
+			return frappe.db.sql("""select name, credit_to, outstanding_amount 
 				from `tabPurchase Invoice` where docstatus = 1 and company = %s 
 				and outstanding_amount > 0 %s""" % ('%s', cond), self.doc.company)
 
 @frappe.whitelist()
 def get_default_bank_cash_account(company, voucher_type):
 	from erpnext.accounts.utils import get_balance_on
-	account = frappe.conn.get_value("Company", company,
+	account = frappe.db.get_value("Company", company,
 		voucher_type=="Bank Voucher" and "default_bank_account" or "default_cash_account")
 	if account:
 		return {
@@ -412,27 +412,27 @@
 def get_opening_accounts(company):
 	"""get all balance sheet accounts for opening entry"""
 	from erpnext.accounts.utils import get_balance_on
-	accounts = frappe.conn.sql_list("""select name from tabAccount 
+	accounts = frappe.db.sql_list("""select name from tabAccount 
 		where group_or_ledger='Ledger' and is_pl_account='No' and company=%s""", company)
 	
 	return [{"account": a, "balance": get_balance_on(a)} for a in accounts]
 	
 def get_against_purchase_invoice(doctype, txt, searchfield, start, page_len, filters):
-	return frappe.conn.sql("""select name, credit_to, outstanding_amount, bill_no, bill_date 
+	return frappe.db.sql("""select name, credit_to, outstanding_amount, bill_no, bill_date 
 		from `tabPurchase Invoice` where credit_to = %s and docstatus = 1 
 		and outstanding_amount > 0 and %s like %s order by name desc limit %s, %s""" %
 		("%s", searchfield, "%s", "%s", "%s"), 
 		(filters["account"], "%%%s%%" % txt, start, page_len))
 		
 def get_against_sales_invoice(doctype, txt, searchfield, start, page_len, filters):
-	return frappe.conn.sql("""select name, debit_to, outstanding_amount 
+	return frappe.db.sql("""select name, debit_to, outstanding_amount 
 		from `tabSales Invoice` where debit_to = %s and docstatus = 1 
 		and outstanding_amount > 0 and `%s` like %s order by name desc limit %s, %s""" %
 		("%s", searchfield, "%s", "%s", "%s"), 
 		(filters["account"], "%%%s%%" % txt, start, page_len))
 		
 def get_against_jv(doctype, txt, searchfield, start, page_len, filters):
-	return frappe.conn.sql("""select jv.name, jv.posting_date, jv.user_remark 
+	return frappe.db.sql("""select jv.name, jv.posting_date, jv.user_remark 
 		from `tabJournal Voucher` jv, `tabJournal Voucher Detail` jv_detail 
 		where jv_detail.parent = jv.name and jv_detail.account = %s and jv.docstatus = 1 
 		and jv.%s like %s order by jv.name desc limit %s, %s""" % 
@@ -443,7 +443,7 @@
 def get_outstanding(args):
 	args = eval(args)
 	if args.get("doctype") == "Journal Voucher" and args.get("account"):
-		against_jv_amount = frappe.conn.sql("""
+		against_jv_amount = frappe.db.sql("""
 			select sum(ifnull(debit, 0)) - sum(ifnull(credit, 0)) 
 			from `tabJournal Voucher Detail` where parent=%s and account=%s 
 			and ifnull(against_invoice, '')='' and ifnull(against_voucher, '')=''
@@ -457,11 +457,11 @@
 		
 	elif args.get("doctype") == "Sales Invoice":
 		return {
-			"credit": flt(frappe.conn.get_value("Sales Invoice", args["docname"], 
+			"credit": flt(frappe.db.get_value("Sales Invoice", args["docname"], 
 				"outstanding_amount"))
 		}
 	elif args.get("doctype") == "Purchase Invoice":
 		return {
-			"debit": flt(frappe.conn.get_value("Purchase Invoice", args["docname"], 
+			"debit": flt(frappe.db.get_value("Purchase Invoice", args["docname"], 
 				"outstanding_amount"))
 		}
diff --git a/erpnext/accounts/doctype/journal_voucher/test_journal_voucher.py b/erpnext/accounts/doctype/journal_voucher/test_journal_voucher.py
index 4497726..35e2155 100644
--- a/erpnext/accounts/doctype/journal_voucher/test_journal_voucher.py
+++ b/erpnext/accounts/doctype/journal_voucher/test_journal_voucher.py
@@ -13,7 +13,7 @@
 		jv_invoice.insert()
 		jv_invoice.submit()
 		
-		self.assertTrue(not frappe.conn.sql("""select name from `tabJournal Voucher Detail`
+		self.assertTrue(not frappe.db.sql("""select name from `tabJournal Voucher Detail`
 			where against_jv=%s""", jv_invoice.doc.name))
 		
 		jv_payment = frappe.bean(copy=test_records[0])
@@ -21,16 +21,16 @@
 		jv_payment.insert()
 		jv_payment.submit()
 		
-		self.assertTrue(frappe.conn.sql("""select name from `tabJournal Voucher Detail`
+		self.assertTrue(frappe.db.sql("""select name from `tabJournal Voucher Detail`
 			where against_jv=%s""", jv_invoice.doc.name))
 			
-		self.assertTrue(frappe.conn.sql("""select name from `tabJournal Voucher Detail`
+		self.assertTrue(frappe.db.sql("""select name from `tabJournal Voucher Detail`
 			where against_jv=%s and credit=400""", jv_invoice.doc.name))
 		
 		# cancel jv_invoice
 		jv_invoice.cancel()
 		
-		self.assertTrue(not frappe.conn.sql("""select name from `tabJournal Voucher Detail`
+		self.assertTrue(not frappe.db.sql("""select name from `tabJournal Voucher Detail`
 			where against_jv=%s""", jv_invoice.doc.name))
 	
 	def test_jv_against_stock_account(self):
@@ -47,7 +47,7 @@
 		set_perpetual_inventory(0)
 			
 	def test_monthly_budget_crossed_ignore(self):
-		frappe.conn.set_value("Company", "_Test Company", "monthly_bgt_flag", "Ignore")
+		frappe.db.set_value("Company", "_Test Company", "monthly_bgt_flag", "Ignore")
 		self.clear_account_balance()
 		
 		jv = frappe.bean(copy=test_records[0])
@@ -57,12 +57,12 @@
 		jv.doclist[1].credit = 20000.0
 		jv.insert()
 		jv.submit()
-		self.assertTrue(frappe.conn.get_value("GL Entry", 
+		self.assertTrue(frappe.db.get_value("GL Entry", 
 			{"voucher_type": "Journal Voucher", "voucher_no": jv.doc.name}))
 			
 	def test_monthly_budget_crossed_stop(self):
 		from erpnext.accounts.utils import BudgetError
-		frappe.conn.set_value("Company", "_Test Company", "monthly_bgt_flag", "Stop")
+		frappe.db.set_value("Company", "_Test Company", "monthly_bgt_flag", "Stop")
 		self.clear_account_balance()
 		
 		jv = frappe.bean(copy=test_records[0])
@@ -74,14 +74,14 @@
 		
 		self.assertRaises(BudgetError, jv.submit)
 		
-		frappe.conn.set_value("Company", "_Test Company", "monthly_bgt_flag", "Ignore")
+		frappe.db.set_value("Company", "_Test Company", "monthly_bgt_flag", "Ignore")
 		
 	def test_yearly_budget_crossed_stop(self):
 		from erpnext.accounts.utils import BudgetError
 		self.clear_account_balance()
 		self.test_monthly_budget_crossed_ignore()
 		
-		frappe.conn.set_value("Company", "_Test Company", "yearly_bgt_flag", "Stop")
+		frappe.db.set_value("Company", "_Test Company", "yearly_bgt_flag", "Stop")
 		
 		jv = frappe.bean(copy=test_records[0])
 		jv.doc.posting_date = "2013-08-12"
@@ -93,11 +93,11 @@
 		
 		self.assertRaises(BudgetError, jv.submit)
 		
-		frappe.conn.set_value("Company", "_Test Company", "yearly_bgt_flag", "Ignore")
+		frappe.db.set_value("Company", "_Test Company", "yearly_bgt_flag", "Ignore")
 		
 	def test_monthly_budget_on_cancellation(self):
 		from erpnext.accounts.utils import BudgetError
-		frappe.conn.set_value("Company", "_Test Company", "monthly_bgt_flag", "Stop")
+		frappe.db.set_value("Company", "_Test Company", "monthly_bgt_flag", "Stop")
 		self.clear_account_balance()
 		
 		jv = frappe.bean(copy=test_records[0])
@@ -107,7 +107,7 @@
 		jv.doclist[2].debit = 30000.0
 		jv.submit()
 		
-		self.assertTrue(frappe.conn.get_value("GL Entry", 
+		self.assertTrue(frappe.db.get_value("GL Entry", 
 			{"voucher_type": "Journal Voucher", "voucher_no": jv.doc.name}))
 		
 		jv1 = frappe.bean(copy=test_records[0])
@@ -117,15 +117,15 @@
 		jv1.doclist[1].credit = 40000.0
 		jv1.submit()
 		
-		self.assertTrue(frappe.conn.get_value("GL Entry", 
+		self.assertTrue(frappe.db.get_value("GL Entry", 
 			{"voucher_type": "Journal Voucher", "voucher_no": jv1.doc.name}))
 		
 		self.assertRaises(BudgetError, jv.cancel)
 		
-		frappe.conn.set_value("Company", "_Test Company", "monthly_bgt_flag", "Ignore")
+		frappe.db.set_value("Company", "_Test Company", "monthly_bgt_flag", "Ignore")
 		
 	def clear_account_balance(self):
-		frappe.conn.sql("""delete from `tabGL Entry`""")
+		frappe.db.sql("""delete from `tabGL Entry`""")
 		
 
 test_records = [
diff --git a/erpnext/accounts/doctype/mis_control/mis_control.py b/erpnext/accounts/doctype/mis_control/mis_control.py
index 102fb01..b398716 100644
--- a/erpnext/accounts/doctype/mis_control/mis_control.py
+++ b/erpnext/accounts/doctype/mis_control/mis_control.py
@@ -33,7 +33,7 @@
 		ret['company'] = get_companies()
 
 		#--- to get fiscal year and start_date of that fiscal year -----
-		res = frappe.conn.sql("select name, year_start_date from `tabFiscal Year`")
+		res = frappe.db.sql("select name, year_start_date from `tabFiscal Year`")
 		ret['fiscal_year'] = [r[0] for r in res]
 		ret['start_dates'] = {}
 		for r in res:
@@ -41,7 +41,7 @@
 			
 		#--- from month and to month (for MIS - Comparison Report) -------
 		month_list = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
-		fiscal_start_month = frappe.conn.sql("select MONTH(year_start_date) from `tabFiscal Year` where name = %s",(frappe.defaults.get_global_default("fiscal_year")))
+		fiscal_start_month = frappe.db.sql("select MONTH(year_start_date) from `tabFiscal Year` where name = %s",(frappe.defaults.get_global_default("fiscal_year")))
 		fiscal_start_month = fiscal_start_month and fiscal_start_month[0][0] or 1
 		mon = ['']
 		for i in range(fiscal_start_month,13): mon.append(month_list[i-1])
@@ -76,7 +76,7 @@
 		return self.return_data
 
 	def get_children(self, parent_account, level, pl, company, fy):
-		cl = frappe.conn.sql("select distinct account_name, name, debit_or_credit, lft, rgt from `tabAccount` where ifnull(parent_account, '') = %s and ifnull(is_pl_account, 'No')=%s and company=%s and docstatus != 2 order by name asc", (parent_account, pl, company))
+		cl = frappe.db.sql("select distinct account_name, name, debit_or_credit, lft, rgt from `tabAccount` where ifnull(parent_account, '') = %s and ifnull(is_pl_account, 'No')=%s and company=%s and docstatus != 2 order by name asc", (parent_account, pl, company))
 		level0_diff = [0 for p in self.period_list]
 		if pl=='Yes' and level==0: # switch for income & expenses
 			cl = [c for c in cl]
@@ -123,7 +123,7 @@
 							self.return_data.append([4, 'Total '+c[0]] + totals)
 
 	def define_periods(self, year, period):	
-		ysd = frappe.conn.sql("select year_start_date from `tabFiscal Year` where name=%s", year)
+		ysd = frappe.db.sql("select year_start_date from `tabFiscal Year` where name=%s", year)
 		ysd = ysd and ysd[0][0] or ''
 
 		self.ysd = ysd
diff --git a/erpnext/accounts/doctype/payment_to_invoice_matching_tool/payment_to_invoice_matching_tool.py b/erpnext/accounts/doctype/payment_to_invoice_matching_tool/payment_to_invoice_matching_tool.py
index ceea672..f6a31a0 100644
--- a/erpnext/accounts/doctype/payment_to_invoice_matching_tool/payment_to_invoice_matching_tool.py
+++ b/erpnext/accounts/doctype/payment_to_invoice_matching_tool/payment_to_invoice_matching_tool.py
@@ -16,17 +16,17 @@
 	
 	def set_account_type(self):
 		self.doc.account_type = self.doc.account and \
-			frappe.conn.get_value("Account", self.doc.account, "debit_or_credit").lower() or ""
+			frappe.db.get_value("Account", self.doc.account, "debit_or_credit").lower() or ""
 		
 	def get_voucher_details(self):
-		total_amount = frappe.conn.sql("""select sum(%s) from `tabGL Entry` 
+		total_amount = frappe.db.sql("""select sum(%s) from `tabGL Entry` 
 			where voucher_type = %s and voucher_no = %s 
 			and account = %s""" % 
 			(self.doc.account_type, '%s', '%s', '%s'), 
 			(self.doc.voucher_type, self.doc.voucher_no, self.doc.account))
 			
 		total_amount = total_amount and flt(total_amount[0][0]) or 0
-		reconciled_payment = frappe.conn.sql("""
+		reconciled_payment = frappe.db.sql("""
 			select sum(ifnull(%s, 0)) - sum(ifnull(%s, 0)) from `tabGL Entry` where 
 			against_voucher = %s and voucher_no != %s
 			and account = %s""" % 
@@ -63,7 +63,7 @@
 		cond += self.doc.amt_less_than and \
 			' and t2.' + dc+' <= ' + self.doc.amt_less_than or ''
 
-		gle = frappe.conn.sql("""
+		gle = frappe.db.sql("""
 			select t1.name as voucher_no, t1.posting_date, t1.total_debit as total_amt, 
 			 	sum(ifnull(t2.credit, 0)) - sum(ifnull(t2.debit, 0)) as amt_due, t1.remark,
 			 	t2.against_account, t2.name as voucher_detail_no
@@ -99,7 +99,7 @@
 			2. split into multiple rows if partially adjusted, assign against voucher
 			3. submit payment voucher
 		"""
-		if not self.doc.voucher_no or not frappe.conn.sql("""select name from `tab%s` 
+		if not self.doc.voucher_no or not frappe.db.sql("""select name from `tab%s` 
 				where name = %s""" % (self.doc.voucher_type, '%s'), self.doc.voucher_no):
 			msgprint("Please select valid Voucher No to proceed", raise_exception=1)
 		
@@ -130,7 +130,7 @@
 def gl_entry_details(doctype, txt, searchfield, start, page_len, filters):
 	from erpnext.controllers.queries import get_match_cond
 	
-	return frappe.conn.sql("""select gle.voucher_no, gle.posting_date, 
+	return frappe.db.sql("""select gle.voucher_no, gle.posting_date, 
 		gle.%(account_type)s from `tabGL Entry` gle
 	    where gle.account = '%(acc)s' 
 	    	and gle.voucher_type = '%(dt)s'
diff --git a/erpnext/accounts/doctype/period_closing_voucher/period_closing_voucher.py b/erpnext/accounts/doctype/period_closing_voucher/period_closing_voucher.py
index 753b7db..98befa0 100644
--- a/erpnext/accounts/doctype/period_closing_voucher/period_closing_voucher.py
+++ b/erpnext/accounts/doctype/period_closing_voucher/period_closing_voucher.py
@@ -21,11 +21,11 @@
 		self.make_gl_entries()
 
 	def on_cancel(self):
-		frappe.conn.sql("""delete from `tabGL Entry` 
+		frappe.db.sql("""delete from `tabGL Entry` 
 			where voucher_type = 'Period Closing Voucher' and voucher_no=%s""", self.doc.name)
 
 	def validate_account_head(self):
-		debit_or_credit, is_pl_account = frappe.conn.get_value("Account", 
+		debit_or_credit, is_pl_account = frappe.db.get_value("Account", 
 			self.doc.closing_account_head, ["debit_or_credit", "is_pl_account"])
 			
 		if debit_or_credit != 'Credit' or is_pl_account != 'No':
@@ -36,7 +36,7 @@
 		from erpnext.accounts.utils import get_fiscal_year
 		self.year_start_date = get_fiscal_year(self.doc.posting_date, self.doc.fiscal_year)[1]
 
-		pce = frappe.conn.sql("""select name from `tabPeriod Closing Voucher`
+		pce = frappe.db.sql("""select name from `tabPeriod Closing Voucher`
 			where posting_date > %s and fiscal_year = %s and docstatus = 1""", 
 			(self.doc.posting_date, self.doc.fiscal_year))
 		if pce and pce[0][0]:
@@ -44,7 +44,7 @@
 				  _("has been made after posting date") + ": " + self.doc.posting_date)
 		 
 	def validate_pl_balances(self):
-		income_bal = frappe.conn.sql("""
+		income_bal = frappe.db.sql("""
 			select sum(ifnull(t1.debit,0))-sum(ifnull(t1.credit,0)) 
 			from `tabGL Entry` t1, tabAccount t2 
 			where t1.account = t2.name and t1.posting_date between %s and %s 
@@ -52,7 +52,7 @@
 			and t2.docstatus < 2 and t2.company = %s""", 
 			(self.year_start_date, self.doc.posting_date, self.doc.company))
 			
-		expense_bal = frappe.conn.sql("""
+		expense_bal = frappe.db.sql("""
 			select sum(ifnull(t1.debit,0))-sum(ifnull(t1.credit,0))
 			from `tabGL Entry` t1, tabAccount t2 
 			where t1.account = t2.name and t1.posting_date between %s and %s
@@ -68,7 +68,7 @@
 		
 	def get_pl_balances(self):
 		"""Get balance for pl accounts"""
-		return frappe.conn.sql("""
+		return frappe.db.sql("""
 			select t1.account, sum(ifnull(t1.debit,0))-sum(ifnull(t1.credit,0)) as balance
 			from `tabGL Entry` t1, `tabAccount` t2 
 			where t1.account = t2.name and ifnull(t2.is_pl_account, 'No') = 'Yes'
diff --git a/erpnext/accounts/doctype/period_closing_voucher/test_period_closing_voucher.py b/erpnext/accounts/doctype/period_closing_voucher/test_period_closing_voucher.py
index 5039e88..9b62af1 100644
--- a/erpnext/accounts/doctype/period_closing_voucher/test_period_closing_voucher.py
+++ b/erpnext/accounts/doctype/period_closing_voucher/test_period_closing_voucher.py
@@ -9,7 +9,7 @@
 class TestPeriodClosingVoucher(unittest.TestCase):
 	def test_closing_entry(self):
 		# clear GL Entries
-		frappe.conn.sql("""delete from `tabGL Entry`""")
+		frappe.db.sql("""delete from `tabGL Entry`""")
 		
 		from erpnext.accounts.doctype.journal_voucher.test_journal_voucher import test_records as jv_records
 		jv = frappe.bean(copy=jv_records[2])
@@ -27,7 +27,7 @@
 		pcv.insert()
 		pcv.submit()
 		
-		gl_entries = frappe.conn.sql("""select account, debit, credit
+		gl_entries = frappe.db.sql("""select account, debit, credit
 			from `tabGL Entry` where voucher_type='Period Closing Voucher' and voucher_no=%s
 			order by account asc, debit asc""", pcv.doc.name, as_dict=1)
 
diff --git a/erpnext/accounts/doctype/pos_setting/pos_setting.py b/erpnext/accounts/doctype/pos_setting/pos_setting.py
index e743fb3..69228fd 100755
--- a/erpnext/accounts/doctype/pos_setting/pos_setting.py
+++ b/erpnext/accounts/doctype/pos_setting/pos_setting.py
@@ -23,7 +23,7 @@
 		self.validate_all_link_fields()
 		
 	def check_for_duplicate(self):
-		res = frappe.conn.sql("""select name, user from `tabPOS Setting` 
+		res = frappe.db.sql("""select name, user from `tabPOS Setting` 
 			where ifnull(user, '') = %s and name != %s and company = %s""", 
 			(self.doc.user, self.doc.name, self.doc.company))
 		if res:
@@ -46,14 +46,14 @@
 		
 		for link_dt, dn_list in accounts.items():
 			for link_dn in dn_list:
-				if link_dn and not frappe.conn.exists({"doctype": link_dt, 
+				if link_dn and not frappe.db.exists({"doctype": link_dt, 
 						"company": self.doc.company, "name": link_dn}):
 					frappe.throw(link_dn +_(" does not belong to ") + self.doc.company)
 
 	def on_update(self):
 		frappe.defaults.clear_default("is_pos")
 
-		pos_view_users = frappe.conn.sql_list("""select user from `tabPOS Setting`""")
+		pos_view_users = frappe.db.sql_list("""select user from `tabPOS Setting`""")
 		for user in pos_view_users:
 			if user:
 				frappe.defaults.set_user_default("is_pos", 1, user)
diff --git a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
index 450fdc3..5717dfb 100644
--- a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
+++ b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
@@ -73,7 +73,7 @@
 	def check_active_purchase_items(self):
 		for d in getlist(self.doclist, 'entries'):
 			if d.item_code:		# extra condn coz item_code is not mandatory in PV
-				valid_item = frappe.conn.sql("select docstatus,is_purchase_item from tabItem where name = %s",d.item_code)
+				valid_item = frappe.db.sql("select docstatus,is_purchase_item from tabItem where name = %s",d.item_code)
 				if valid_item[0][0] == 2:
 					msgprint("Item : '%s' is Inactive, you can restore it from Trash" %(d.item_code))
 					raise Exception
@@ -93,7 +93,7 @@
 	def validate_bill_no(self):
 		if self.doc.bill_no and self.doc.bill_no.lower().strip() \
 				not in ['na', 'not applicable', 'none']:
-			b_no = frappe.conn.sql("""select bill_no, name, ifnull(is_opening,'') from `tabPurchase Invoice` 
+			b_no = frappe.db.sql("""select bill_no, name, ifnull(is_opening,'') from `tabPurchase Invoice` 
 				where bill_no = %s and credit_to = %s and docstatus = 1 and name != %s""", 
 				(self.doc.bill_no, self.doc.credit_to, self.doc.name))
 			if b_no and cstr(b_no[0][2]) == cstr(self.doc.is_opening):
@@ -109,7 +109,7 @@
 			self.doc.remarks = "No Remarks"
 
 	def validate_credit_acc(self):
-		acc = frappe.conn.sql("select debit_or_credit, is_pl_account from tabAccount where name = %s", 
+		acc = frappe.db.sql("select debit_or_credit, is_pl_account from tabAccount where name = %s", 
 			self.doc.credit_to)
 		if not acc:
 			msgprint("Account: "+ self.doc.credit_to + "does not exist")
@@ -125,7 +125,7 @@
 	# ------------------------------------------------------------
 	def check_for_acc_head_of_supplier(self): 
 		if self.doc.supplier and self.doc.credit_to:
-			acc_head = frappe.conn.sql("select master_name from `tabAccount` where name = %s", self.doc.credit_to)
+			acc_head = frappe.db.sql("select master_name from `tabAccount` where name = %s", self.doc.credit_to)
 			
 			if (acc_head and cstr(acc_head[0][0]) != cstr(self.doc.supplier)) or (not acc_head and (self.doc.credit_to != cstr(self.doc.supplier) + " - " + self.company_abbr)):
 				msgprint("Credit To: %s do not match with Supplier: %s for Company: %s.\n If both correctly entered, please select Master Type and Master Name in account master." %(self.doc.credit_to,self.doc.supplier,self.doc.company), raise_exception=1)
@@ -137,7 +137,7 @@
 		for d in getlist(self.doclist,'entries'):
 			if d.purchase_order and not d.purchase_order in check_list and not d.purchase_receipt:
 				check_list.append(d.purhcase_order)
-				stopped = frappe.conn.sql("select name from `tabPurchase Order` where status = 'Stopped' and name = '%s'" % d.purchase_order)
+				stopped = frappe.db.sql("select name from `tabPurchase Order` where status = 'Stopped' and name = '%s'" % d.purchase_order)
 				if stopped:
 					msgprint("One cannot do any transaction against 'Purchase Order' : %s, it's status is 'Stopped'" % (d.purhcase_order))
 					raise Exception
@@ -218,14 +218,14 @@
 		self.doc.against_expense_account = ",".join(against_accounts)
 
 	def po_required(self):
-		if frappe.conn.get_value("Buying Settings", None, "po_required") == 'Yes':
+		if frappe.db.get_value("Buying Settings", None, "po_required") == 'Yes':
 			 for d in getlist(self.doclist,'entries'):
 				 if not d.purchase_order:
 					 msgprint("Purchse Order No. required against item %s"%d.item_code)
 					 raise Exception
 
 	def pr_required(self):
-		if frappe.conn.get_value("Buying Settings", None, "pr_required") == 'Yes':
+		if frappe.db.get_value("Buying Settings", None, "pr_required") == 'Yes':
 			 for d in getlist(self.doclist,'entries'):
 				 if not d.purchase_receipt:
 					 msgprint("Purchase Receipt No. required against item %s"%d.item_code)
@@ -238,11 +238,11 @@
 	def check_prev_docstatus(self):
 		for d in getlist(self.doclist,'entries'):
 			if d.purchase_order:
-				submitted = frappe.conn.sql("select name from `tabPurchase Order` where docstatus = 1 and name = '%s'" % d.purchase_order)
+				submitted = frappe.db.sql("select name from `tabPurchase Order` where docstatus = 1 and name = '%s'" % d.purchase_order)
 				if not submitted:
 					frappe.throw("Purchase Order : "+ cstr(d.purchase_order) +" is not submitted")
 			if d.purchase_receipt:
-				submitted = frappe.conn.sql("select name from `tabPurchase Receipt` where docstatus = 1 and name = '%s'" % d.purchase_receipt)
+				submitted = frappe.db.sql("select name from `tabPurchase Receipt` where docstatus = 1 and name = '%s'" % d.purchase_receipt)
 				if not submitted:
 					frappe.throw("Purchase Receipt : "+ cstr(d.purchase_receipt) +" is not submitted")
 					
@@ -414,12 +414,12 @@
 	def update_raw_material_cost(self):
 		if self.sub_contracted_items:
 			for d in self.doclist.get({"parentfield": "entries"}):
-				rm_cost = frappe.conn.sql("""select raw_material_cost / quantity 
+				rm_cost = frappe.db.sql("""select raw_material_cost / quantity 
 					from `tabBOM` where item = %s and is_default = 1 and docstatus = 1 
 					and is_active = 1 """, (d.item_code,))
 				rm_cost = rm_cost and flt(rm_cost[0][0]) or 0
 				
-				d.conversion_factor = d.conversion_factor or flt(frappe.conn.get_value(
+				d.conversion_factor = d.conversion_factor or flt(frappe.db.get_value(
 					"UOM Conversion Detail", {"parent": d.item_code, "uom": d.uom}, 
 					"conversion_factor")) or 1
 		
@@ -432,7 +432,7 @@
 	# expense account can be any Debit account, 
 	# but can also be a Liability account with account_type='Expense Account' in special circumstances. 
 	# Hence the first condition is an "OR"
-	return frappe.conn.sql("""select tabAccount.name from `tabAccount` 
+	return frappe.db.sql("""select tabAccount.name from `tabAccount` 
 			where (tabAccount.debit_or_credit="Debit" 
 					or tabAccount.account_type = "Expense Account")
 				and tabAccount.group_or_ledger="Ledger" 
diff --git a/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py b/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py
index 85a9f41..b5942e3 100644
--- a/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py
+++ b/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py
@@ -36,7 +36,7 @@
 			"_Test Account VAT - _TC": [156.25, 0],
 			"_Test Account Discount - _TC": [0, 168.03],
 		}
-		gl_entries = frappe.conn.sql("""select account, debit, credit from `tabGL Entry`
+		gl_entries = frappe.db.sql("""select account, debit, credit from `tabGL Entry`
 			where voucher_type = 'Purchase Invoice' and voucher_no = %s""", dl[0].name, as_dict=1)
 		for d in gl_entries:
 			self.assertEqual([d.debit, d.credit], expected_gl_entries.get(d.account))
@@ -49,7 +49,7 @@
 		pi.insert()
 		pi.submit()
 		
-		gl_entries = frappe.conn.sql("""select account, debit, credit
+		gl_entries = frappe.db.sql("""select account, debit, credit
 			from `tabGL Entry` where voucher_type='Purchase Invoice' and voucher_no=%s
 			order by account asc""", pi.doc.name, as_dict=1)
 		self.assertTrue(gl_entries)
@@ -81,7 +81,7 @@
 		pi.insert()
 		pi.submit()
 		
-		gl_entries = frappe.conn.sql("""select account, debit, credit
+		gl_entries = frappe.db.sql("""select account, debit, credit
 			from `tabGL Entry` where voucher_type='Purchase Invoice' and voucher_no=%s
 			order by account asc""", pi.doc.name, as_dict=1)
 		self.assertTrue(gl_entries)
@@ -187,17 +187,17 @@
 		pi.submit()
 		pi.load_from_db()
 		
-		self.assertTrue(frappe.conn.sql("""select name from `tabJournal Voucher Detail`
+		self.assertTrue(frappe.db.sql("""select name from `tabJournal Voucher Detail`
 			where against_voucher=%s""", pi.doc.name))
 		
-		self.assertTrue(frappe.conn.sql("""select name from `tabJournal Voucher Detail`
+		self.assertTrue(frappe.db.sql("""select name from `tabJournal Voucher Detail`
 			where against_voucher=%s and debit=300""", pi.doc.name))
 			
 		self.assertEqual(pi.doc.outstanding_amount, 1212.30)
 		
 		pi.cancel()
 		
-		self.assertTrue(not frappe.conn.sql("""select name from `tabJournal Voucher Detail`
+		self.assertTrue(not frappe.db.sql("""select name from `tabJournal Voucher Detail`
 			where against_voucher=%s""", pi.doc.name))
 	
 test_records = [
diff --git a/erpnext/accounts/doctype/sales_invoice/pos.py b/erpnext/accounts/doctype/sales_invoice/pos.py
index 593996b..2286ed6 100644
--- a/erpnext/accounts/doctype/sales_invoice/pos.py
+++ b/erpnext/accounts/doctype/sales_invoice/pos.py
@@ -21,7 +21,7 @@
 		condition += " and CONCAT(i.name, i.item_name) like %(name)s"
 		args["name"] = "%%%s%%" % item
 
-	return frappe.conn.sql("""select i.name, i.item_name, i.image, 
+	return frappe.db.sql("""select i.name, i.item_name, i.image, 
 		item_det.price_list_rate, item_det.currency 
 		from `tabItem` i LEFT JOIN 
 			(select item_code, price_list_rate, currency from 
@@ -34,12 +34,12 @@
 @frappe.whitelist()
 def get_item_code(barcode_serial_no):
 	input_via = "serial_no"
-	item_code = frappe.conn.sql("""select name, item_code from `tabSerial No` where 
+	item_code = frappe.db.sql("""select name, item_code from `tabSerial No` where 
 		name=%s""", (barcode_serial_no), as_dict=1)
 
 	if not item_code:
 		input_via = "barcode"
-		item_code = frappe.conn.sql("""select name from `tabItem` where barcode=%s""",
+		item_code = frappe.db.sql("""select name from `tabItem` where barcode=%s""",
 			(barcode_serial_no), as_dict=1)
 
 	if item_code:
@@ -49,4 +49,4 @@
 
 @frappe.whitelist()
 def get_mode_of_payment():
-	return frappe.conn.sql("""select name from `tabMode of Payment`""", as_dict=1)
\ No newline at end of file
+	return frappe.db.sql("""select name from `tabMode of Payment`""", as_dict=1)
\ No newline at end of file
diff --git a/erpnext/accounts/doctype/sales_invoice/sales_invoice.py b/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
index bd82a3c..6bccd03 100644
--- a/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
+++ b/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
@@ -167,7 +167,7 @@
 	def validate_time_logs_are_submitted(self):
 		for d in self.doclist.get({"doctype":"Sales Invoice Item"}):
 			if d.time_log_batch:
-				status = frappe.conn.get_value("Time Log Batch", d.time_log_batch, "status")
+				status = frappe.db.get_value("Time Log Batch", d.time_log_batch, "status")
 				if status!="Submitted":
 					frappe.msgprint(_("Time Log Batch status must be 'Submitted'") + ":" + d.time_log_batch,
 						raise_exception=True)
@@ -202,7 +202,7 @@
 
 			# fetch terms	
 			if self.doc.tc_name and not self.doc.terms:
-				self.doc.terms = frappe.conn.get_value("Terms and Conditions", self.doc.tc_name, "terms")
+				self.doc.terms = frappe.db.get_value("Terms and Conditions", self.doc.tc_name, "terms")
 			
 			# fetch charges
 			if self.doc.charge and not len(self.doclist.get({"parentfield": "other_charges"})):
@@ -213,7 +213,7 @@
 			"Sales Invoice Advance", "advance_adjustment_details", "credit")
 		
 	def get_company_abbr(self):
-		return frappe.conn.sql("select abbr from tabCompany where name=%s", self.doc.company)[0][0]
+		return frappe.db.sql("select abbr from tabCompany where name=%s", self.doc.company)[0][0]
 
 	def update_against_document_in_jv(self):
 		"""
@@ -246,7 +246,7 @@
 	def validate_customer_account(self):
 		"""Validates Debit To Account and Customer Matches"""
 		if self.doc.customer and self.doc.debit_to and not cint(self.doc.is_pos):
-			acc_head = frappe.conn.sql("select master_name from `tabAccount` where name = %s and docstatus != 2", self.doc.debit_to)
+			acc_head = frappe.db.sql("select master_name from `tabAccount` where name = %s and docstatus != 2", self.doc.debit_to)
 			
 			if (acc_head and cstr(acc_head[0][0]) != cstr(self.doc.customer)) or \
 				(not acc_head and (self.doc.debit_to != cstr(self.doc.customer) + " - " + self.get_company_abbr())):
@@ -255,7 +255,7 @@
 
 
 	def validate_debit_acc(self):
-		acc = frappe.conn.sql("select debit_or_credit, is_pl_account from tabAccount where name = '%s' and docstatus != 2" % self.doc.debit_to)
+		acc = frappe.db.sql("select debit_or_credit, is_pl_account from tabAccount where name = '%s' and docstatus != 2" % self.doc.debit_to)
 		if not acc:
 			msgprint("Account: "+ self.doc.debit_to + " does not exist")
 			raise Exception
@@ -270,8 +270,8 @@
 	def validate_fixed_asset_account(self):
 		"""Validate Fixed Asset Account and whether Income Account Entered Exists"""
 		for d in getlist(self.doclist,'entries'):
-			item = frappe.conn.sql("select name,is_asset_item,is_sales_item from `tabItem` where name = '%s' and (ifnull(end_of_life,'')='' or end_of_life = '0000-00-00' or end_of_life >	now())"% d.item_code)
-			acc =	frappe.conn.sql("select account_type from `tabAccount` where name = '%s' and docstatus != 2" % d.income_account)
+			item = frappe.db.sql("select name,is_asset_item,is_sales_item from `tabItem` where name = '%s' and (ifnull(end_of_life,'')='' or end_of_life = '0000-00-00' or end_of_life >	now())"% d.item_code)
+			acc =	frappe.db.sql("select account_type from `tabAccount` where name = '%s' and docstatus != 2" % d.income_account)
 			if not acc:
 				msgprint("Account: "+d.income_account+" does not exist in the system", raise_exception=True)
 			elif item and item[0][1] == 'Yes' and not acc[0][0] == 'Fixed Asset Account':
@@ -332,9 +332,9 @@
 		"""check in manage account if sales order / delivery note required or not."""
 		dic = {'Sales Order':'so_required','Delivery Note':'dn_required'}
 		for i in dic:
-			if frappe.conn.get_value('Selling Settings', None, dic[i]) == 'Yes':
+			if frappe.db.get_value('Selling Settings', None, dic[i]) == 'Yes':
 				for d in getlist(self.doclist,'entries'):
-					if frappe.conn.get_value('Item', d.item_code, 'is_stock_item') == 'Yes' \
+					if frappe.db.get_value('Item', d.item_code, 'is_stock_item') == 'Yes' \
 						and not d.fields[i.lower().replace(' ','_')]:
 						msgprint("%s is mandatory for stock item which is not mentioed against item: %s"%(i,d.item_code), raise_exception=1)
 
@@ -342,7 +342,7 @@
 	def validate_proj_cust(self):
 		"""check for does customer belong to same project as entered.."""
 		if self.doc.project_name and self.doc.customer:
-			res = frappe.conn.sql("select name from `tabProject` where name = '%s' and (customer = '%s' or ifnull(customer,'')='')"%(self.doc.project_name, self.doc.customer))
+			res = frappe.db.sql("select name from `tabProject` where name = '%s' and (customer = '%s' or ifnull(customer,'')='')"%(self.doc.project_name, self.doc.customer))
 			if not res:
 				msgprint("Customer - %s does not belong to project - %s. \n\nIf you want to use project for multiple customers then please make customer details blank in that project."%(self.doc.customer,self.doc.project_name))
 				raise Exception
@@ -377,28 +377,28 @@
 	def validate_c_form(self):
 		""" Blank C-form no if C-form applicable marked as 'No'"""
 		if self.doc.amended_from and self.doc.c_form_applicable == 'No' and self.doc.c_form_no:
-			frappe.conn.sql("""delete from `tabC-Form Invoice Detail` where invoice_no = %s
+			frappe.db.sql("""delete from `tabC-Form Invoice Detail` where invoice_no = %s
 					and parent = %s""", (self.doc.amended_from,	self.doc.c_form_no))
 
-			frappe.conn.set(self.doc, 'c_form_no', '')
+			frappe.db.set(self.doc, 'c_form_no', '')
 			
 	def update_current_stock(self):
 		for d in getlist(self.doclist, 'entries'):
 			if d.item_code and d.warehouse:
-				bin = frappe.conn.sql("select actual_qty from `tabBin` where item_code = %s and warehouse = %s", (d.item_code, d.warehouse), as_dict = 1)
+				bin = frappe.db.sql("select actual_qty from `tabBin` where item_code = %s and warehouse = %s", (d.item_code, d.warehouse), as_dict = 1)
 				d.actual_qty = bin and flt(bin[0]['actual_qty']) or 0
 
 		for d in getlist(self.doclist, 'packing_details'):
-			bin = frappe.conn.sql("select actual_qty, projected_qty from `tabBin` where item_code =	%s and warehouse = %s", (d.item_code, d.warehouse), as_dict = 1)
+			bin = frappe.db.sql("select actual_qty, projected_qty from `tabBin` where item_code =	%s and warehouse = %s", (d.item_code, d.warehouse), as_dict = 1)
 			d.actual_qty = bin and flt(bin[0]['actual_qty']) or 0
 			d.projected_qty = bin and flt(bin[0]['projected_qty']) or 0
 	 
 	
 	def get_warehouse(self):
-		w = frappe.conn.sql("select warehouse from `tabPOS Setting` where ifnull(user,'') = '%s' and company = '%s'" % (frappe.session['user'], self.doc.company))
+		w = frappe.db.sql("select warehouse from `tabPOS Setting` where ifnull(user,'') = '%s' and company = '%s'" % (frappe.session['user'], self.doc.company))
 		w = w and w[0][0] or ''
 		if not w:
-			ps = frappe.conn.sql("select name, warehouse from `tabPOS Setting` where ifnull(user,'') = '' and company = '%s'" % self.doc.company)
+			ps = frappe.db.sql("select name, warehouse from `tabPOS Setting` where ifnull(user,'') = '' and company = '%s'" % self.doc.company)
 			if not ps:
 				msgprint("To make POS entry, please create POS Setting from Accounts --> POS Setting page and refresh the system.", raise_exception=True)
 			elif not ps[0][1]:
@@ -425,25 +425,25 @@
 		if cint(self.doc.is_pos) == 1:
 			if flt(self.doc.paid_amount) == 0:
 				if self.doc.cash_bank_account: 
-					frappe.conn.set(self.doc, 'paid_amount', 
+					frappe.db.set(self.doc, 'paid_amount', 
 						(flt(self.doc.grand_total) - flt(self.doc.write_off_amount)))
 				else:
 					# show message that the amount is not paid
-					frappe.conn.set(self.doc,'paid_amount',0)
+					frappe.db.set(self.doc,'paid_amount',0)
 					frappe.msgprint("Note: Payment Entry will not be created since 'Cash/Bank Account' was not specified.")
 		else:
-			frappe.conn.set(self.doc,'paid_amount',0)
+			frappe.db.set(self.doc,'paid_amount',0)
 		
 	def check_prev_docstatus(self):
 		for d in getlist(self.doclist,'entries'):
 			if d.sales_order:
-				submitted = frappe.conn.sql("select name from `tabSales Order` where docstatus = 1 and name = '%s'" % d.sales_order)
+				submitted = frappe.db.sql("select name from `tabSales Order` where docstatus = 1 and name = '%s'" % d.sales_order)
 				if not submitted:
 					msgprint("Sales Order : "+ cstr(d.sales_order) +" is not submitted")
 					raise Exception , "Validation Error."
 
 			if d.delivery_note:
-				submitted = frappe.conn.sql("select name from `tabDelivery Note` where docstatus = 1 and name = '%s'" % d.delivery_note)
+				submitted = frappe.db.sql("select name from `tabDelivery Note` where docstatus = 1 and name = '%s'" % d.delivery_note)
 				if not submitted:
 					msgprint("Delivery Note : "+ cstr(d.delivery_note) +" is not submitted")
 					raise Exception , "Validation Error."
@@ -451,11 +451,11 @@
 	def update_stock_ledger(self):
 		sl_entries = []
 		for d in self.get_item_list():
-			if frappe.conn.get_value("Item", d.item_code, "is_stock_item") == "Yes" \
+			if frappe.db.get_value("Item", d.item_code, "is_stock_item") == "Yes" \
 					and d.warehouse:
 				sl_entries.append(self.get_sl_entries(d, {
 					"actual_qty": -1*flt(d.qty),
-					"stock_uom": frappe.conn.get_value("Item", d.item_code, "stock_uom")
+					"stock_uom": frappe.db.get_value("Item", d.item_code, "stock_uom")
 				}))
 		
 		self.make_sl_entries(sl_entries)
@@ -584,7 +584,7 @@
 	def update_c_form(self):
 		"""Update amended id in C-form"""
 		if self.doc.c_form_no and self.doc.amended_from:
-			frappe.conn.sql("""update `tabC-Form Invoice Detail` set invoice_no = %s,
+			frappe.db.sql("""update `tabC-Form Invoice Detail` set invoice_no = %s,
 				invoice_date = %s, territory = %s, net_total = %s,
 				grand_total = %s where invoice_no = %s and parent = %s""", 
 				(self.doc.name, self.doc.amended_from, self.doc.c_form_no))
@@ -613,13 +613,13 @@
 	def convert_to_recurring(self):
 		if self.doc.convert_into_recurring_invoice:
 			if not self.doc.recurring_id:
-				frappe.conn.set(self.doc, "recurring_id",
+				frappe.db.set(self.doc, "recurring_id",
 					make_autoname("RECINV/.#####"))
 			
 			self.set_next_date()
 
 		elif self.doc.recurring_id:
-			frappe.conn.sql("""update `tabSales Invoice`
+			frappe.db.sql("""update `tabSales Invoice`
 				set convert_into_recurring_invoice = 0
 				where recurring_id = %s""", (self.doc.recurring_id,))
 			
@@ -649,7 +649,7 @@
 		next_date = get_next_date(self.doc.posting_date,
 			month_map[self.doc.recurring_type], cint(self.doc.repeat_on_day_of_month))
 		
-		frappe.conn.set(self.doc, 'next_date', next_date)
+		frappe.db.set(self.doc, 'next_date', next_date)
 	
 def get_next_date(dt, mcount, day=None):
 	dt = getdate(dt)
@@ -665,14 +665,14 @@
 		and notify the concerned people
 	"""
 	next_date = next_date or nowdate()
-	recurring_invoices = frappe.conn.sql("""select name, recurring_id
+	recurring_invoices = frappe.db.sql("""select name, recurring_id
 		from `tabSales Invoice` where ifnull(convert_into_recurring_invoice, 0)=1
 		and docstatus=1 and next_date=%s
 		and next_date <= ifnull(end_date, '2199-12-31')""", next_date)
 	
 	exception_list = []
 	for ref_invoice, recurring_id in recurring_invoices:
-		if not frappe.conn.sql("""select name from `tabSales Invoice`
+		if not frappe.db.sql("""select name from `tabSales Invoice`
 				where posting_date=%s and recurring_id=%s and docstatus=1""",
 				(next_date, recurring_id)):
 			try:
@@ -680,21 +680,21 @@
 				new_invoice_wrapper = make_new_invoice(ref_wrapper, next_date)
 				send_notification(new_invoice_wrapper)
 				if commit:
-					frappe.conn.commit()
+					frappe.db.commit()
 			except:
 				if commit:
-					frappe.conn.rollback()
+					frappe.db.rollback()
 
-					frappe.conn.begin()
-					frappe.conn.sql("update `tabSales Invoice` set \
+					frappe.db.begin()
+					frappe.db.sql("update `tabSales Invoice` set \
 						convert_into_recurring_invoice = 0 where name = %s", ref_invoice)
 					notify_errors(ref_invoice, ref_wrapper.doc.customer, ref_wrapper.doc.owner)
-					frappe.conn.commit()
+					frappe.db.commit()
 
 				exception_list.append(frappe.get_traceback())
 			finally:
 				if commit:
-					frappe.conn.begin()
+					frappe.db.begin()
 			
 	if exception_list:
 		exception_message = "\n\n".join([cstr(d) for d in exception_list])
@@ -746,7 +746,7 @@
 def notify_errors(inv, customer, owner):
 	from frappe.profile import get_system_managers
 	
-	frappe.sendmail(recipients=get_system_managers() + [frappe.conn.get_value("Profile", owner, "email")],
+	frappe.sendmail(recipients=get_system_managers() + [frappe.db.get_value("Profile", owner, "email")],
 		subject="[Urgent] Error while creating recurring invoice for %s" % inv,
 		message = frappe.get_template("template/emails/recurring_invoice_failed.html").render({
 			"name": inv,
@@ -769,7 +769,7 @@
 
 @frappe.whitelist()
 def get_bank_cash_account(mode_of_payment):
-	val = frappe.conn.get_value("Mode of Payment", mode_of_payment, "default_account")
+	val = frappe.db.get_value("Mode of Payment", mode_of_payment, "default_account")
 	if not val:
 		frappe.msgprint("Default Bank / Cash Account not set in Mode of Payment: %s. Please add a Default Account in Mode of Payment master." % mode_of_payment)
 	return {
@@ -783,7 +783,7 @@
 	# income account can be any Credit account, 
 	# but can also be a Asset account with account_type='Income Account' in special circumstances. 
 	# Hence the first condition is an "OR"
-	return frappe.conn.sql("""select tabAccount.name from `tabAccount` 
+	return frappe.db.sql("""select tabAccount.name from `tabAccount` 
 			where (tabAccount.debit_or_credit="Credit" 
 					or tabAccount.account_type = "Income Account") 
 				and tabAccount.group_or_ledger="Ledger" 
diff --git a/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py b/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py
index f6a67f9..81d5572 100644
--- a/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py
+++ b/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py
@@ -210,7 +210,7 @@
 		si.insert()
 		si.submit()
 
-		gl_entries = frappe.conn.sql("""select account, debit, credit
+		gl_entries = frappe.db.sql("""select account, debit, credit
 			from `tabGL Entry` where voucher_type='Sales Invoice' and voucher_no=%s
 			order by account asc""", si.doc.name, as_dict=1)
 
@@ -238,7 +238,7 @@
 		# cancel
 		si.cancel()
 
-		gle = frappe.conn.sql("""select * from `tabGL Entry` 
+		gle = frappe.db.sql("""select * from `tabGL Entry` 
 			where voucher_type='Sales Invoice' and voucher_no=%s""", si.doc.name)
 
 		self.assertFalse(gle)
@@ -363,7 +363,7 @@
 		self.assertEquals(w.doc.outstanding_amount, w.doc.grand_total)
 		
 	def test_payment(self):
-		frappe.conn.sql("""delete from `tabGL Entry`""")
+		frappe.db.sql("""delete from `tabGL Entry`""")
 		w = self.make()
 		
 		from erpnext.accounts.doctype.journal_voucher.test_journal_voucher \
@@ -374,11 +374,11 @@
 		jv.insert()
 		jv.submit()
 		
-		self.assertEquals(frappe.conn.get_value("Sales Invoice", w.doc.name, "outstanding_amount"),
+		self.assertEquals(frappe.db.get_value("Sales Invoice", w.doc.name, "outstanding_amount"),
 			161.8)
 	
 		jv.cancel()
-		self.assertEquals(frappe.conn.get_value("Sales Invoice", w.doc.name, "outstanding_amount"),
+		self.assertEquals(frappe.db.get_value("Sales Invoice", w.doc.name, "outstanding_amount"),
 			561.8)
 			
 	def test_time_log_batch(self):
@@ -390,18 +390,18 @@
 		si.insert()
 		si.submit()
 		
-		self.assertEquals(frappe.conn.get_value("Time Log Batch", "_T-Time Log Batch-00001",
+		self.assertEquals(frappe.db.get_value("Time Log Batch", "_T-Time Log Batch-00001",
 		 	"status"), "Billed")
 
-		self.assertEquals(frappe.conn.get_value("Time Log", "_T-Time Log-00001", "status"), 
+		self.assertEquals(frappe.db.get_value("Time Log", "_T-Time Log-00001", "status"), 
 			"Billed")
 
 		si.cancel()
 
-		self.assertEquals(frappe.conn.get_value("Time Log Batch", "_T-Time Log Batch-00001", 
+		self.assertEquals(frappe.db.get_value("Time Log Batch", "_T-Time Log Batch-00001", 
 			"status"), "Submitted")
 
-		self.assertEquals(frappe.conn.get_value("Time Log", "_T-Time Log-00001", "status"), 
+		self.assertEquals(frappe.db.get_value("Time Log", "_T-Time Log-00001", "status"), 
 			"Batched for Billing")
 			
 	def test_sales_invoice_gl_entry_without_aii(self):
@@ -411,7 +411,7 @@
 		si.insert()
 		si.submit()
 		
-		gl_entries = frappe.conn.sql("""select account, debit, credit
+		gl_entries = frappe.db.sql("""select account, debit, credit
 			from `tabGL Entry` where voucher_type='Sales Invoice' and voucher_no=%s
 			order by account asc""", si.doc.name, as_dict=1)
 		
@@ -432,7 +432,7 @@
 		# cancel
 		si.cancel()
 		
-		gle = frappe.conn.sql("""select * from `tabGL Entry` 
+		gle = frappe.db.sql("""select * from `tabGL Entry` 
 			where voucher_type='Sales Invoice' and voucher_no=%s""", si.doc.name)
 		
 		self.assertFalse(gle)
@@ -456,7 +456,7 @@
 		si.submit()
 		
 		# check stock ledger entries
-		sle = frappe.conn.sql("""select * from `tabStock Ledger Entry` 
+		sle = frappe.db.sql("""select * from `tabStock Ledger Entry` 
 			where voucher_type = 'Sales Invoice' and voucher_no = %s""", 
 			si.doc.name, as_dict=1)[0]
 		self.assertTrue(sle)
@@ -464,12 +464,12 @@
 			["_Test Item", "_Test Warehouse - _TC", -1.0])
 		
 		# check gl entries
-		gl_entries = frappe.conn.sql("""select account, debit, credit
+		gl_entries = frappe.db.sql("""select account, debit, credit
 			from `tabGL Entry` where voucher_type='Sales Invoice' and voucher_no=%s
 			order by account asc, debit asc""", si.doc.name, as_dict=1)
 		self.assertTrue(gl_entries)
 		
-		stock_in_hand = frappe.conn.get_value("Account", {"master_name": "_Test Warehouse - _TC"})
+		stock_in_hand = frappe.db.get_value("Account", {"master_name": "_Test Warehouse - _TC"})
 				
 		expected_gl_entries = sorted([
 			[si.doc.debit_to, 630.0, 0.0],
@@ -487,7 +487,7 @@
 			self.assertEquals(expected_gl_entries[i][2], gle.credit)
 		
 		si.cancel()
-		gle = frappe.conn.sql("""select * from `tabGL Entry` 
+		gle = frappe.db.sql("""select * from `tabGL Entry` 
 			where voucher_type='Sales Invoice' and voucher_no=%s""", si.doc.name)
 		
 		self.assertFalse(gle)
@@ -520,7 +520,7 @@
 		si.submit()
 		
 		# check stock ledger entries
-		sle = frappe.conn.sql("""select * from `tabStock Ledger Entry` 
+		sle = frappe.db.sql("""select * from `tabStock Ledger Entry` 
 			where voucher_type = 'Sales Invoice' and voucher_no = %s""", 
 			si.doc.name, as_dict=1)[0]
 		self.assertTrue(sle)
@@ -528,7 +528,7 @@
 			["_Test Item", "_Test Warehouse No Account - _TC", -1.0])
 		
 		# check gl entries
-		gl_entries = frappe.conn.sql("""select account, debit, credit
+		gl_entries = frappe.db.sql("""select account, debit, credit
 			from `tabGL Entry` where voucher_type='Sales Invoice' and voucher_no=%s
 			order by account asc, debit asc""", si.doc.name, as_dict=1)
 		self.assertTrue(gl_entries)
@@ -545,7 +545,7 @@
 			self.assertEquals(expected_gl_entries[i][2], gle.credit)
 				
 		si.cancel()
-		gle = frappe.conn.sql("""select * from `tabGL Entry` 
+		gle = frappe.db.sql("""select * from `tabGL Entry` 
 			where voucher_type='Sales Invoice' and voucher_no=%s""", si.doc.name)
 		
 		self.assertFalse(gle)
@@ -561,7 +561,7 @@
 		si.insert()
 		si.submit()
 		
-		gl_entries = frappe.conn.sql("""select account, debit, credit
+		gl_entries = frappe.db.sql("""select account, debit, credit
 			from `tabGL Entry` where voucher_type='Sales Invoice' and voucher_no=%s
 			order by account asc""", si.doc.name, as_dict=1)
 		self.assertTrue(gl_entries)
@@ -588,7 +588,7 @@
 		si.insert()
 		si.submit()
 		
-		gl_entries = frappe.conn.sql("""select account, debit, credit
+		gl_entries = frappe.db.sql("""select account, debit, credit
 			from `tabGL Entry` where voucher_type='Sales Invoice' and voucher_no=%s
 			order by account asc""", si.doc.name, as_dict=1)
 		self.assertTrue(gl_entries)
@@ -626,7 +626,7 @@
 	def _insert_pos_settings(self):
 		from erpnext.accounts.doctype.pos_setting.test_pos_setting \
 			import test_records as pos_setting_test_records
-		frappe.conn.sql("""delete from `tabPOS Setting`""")
+		frappe.db.sql("""delete from `tabPOS Setting`""")
 		
 		ps = frappe.bean(copy=pos_setting_test_records[0])
 		ps.insert()
@@ -653,17 +653,17 @@
 		si.submit()
 		si.load_from_db()
 		
-		self.assertTrue(frappe.conn.sql("""select name from `tabJournal Voucher Detail`
+		self.assertTrue(frappe.db.sql("""select name from `tabJournal Voucher Detail`
 			where against_invoice=%s""", si.doc.name))
 		
-		self.assertTrue(frappe.conn.sql("""select name from `tabJournal Voucher Detail`
+		self.assertTrue(frappe.db.sql("""select name from `tabJournal Voucher Detail`
 			where against_invoice=%s and credit=300""", si.doc.name))
 			
 		self.assertEqual(si.doc.outstanding_amount, 261.8)
 		
 		si.cancel()
 		
-		self.assertTrue(not frappe.conn.sql("""select name from `tabJournal Voucher Detail`
+		self.assertTrue(not frappe.db.sql("""select name from `tabJournal Voucher Detail`
 			where against_invoice=%s""", si.doc.name))
 			
 	def test_recurring_invoice(self):
@@ -762,7 +762,7 @@
 		no_of_months = ({"Monthly": 1, "Quarterly": 3, "Yearly": 12})[base_si.doc.recurring_type]
 		
 		def _test(i):
-			self.assertEquals(i+1, frappe.conn.sql("""select count(*) from `tabSales Invoice`
+			self.assertEquals(i+1, frappe.db.sql("""select count(*) from `tabSales Invoice`
 				where recurring_id=%s and docstatus=1""", base_si.doc.recurring_id)[0][0])
 			
 			next_date = get_next_date(base_si.doc.posting_date, no_of_months, 
@@ -770,7 +770,7 @@
 
 			manage_recurring_invoices(next_date=next_date, commit=False)
 			
-			recurred_invoices = frappe.conn.sql("""select name from `tabSales Invoice`
+			recurred_invoices = frappe.db.sql("""select name from `tabSales Invoice`
 				where recurring_id=%s and docstatus=1 order by name desc""",
 				base_si.doc.recurring_id)
 			
@@ -805,9 +805,9 @@
 			base_si = _test(i)
 			
 	def clear_stock_account_balance(self):
-		frappe.conn.sql("delete from `tabStock Ledger Entry`")
-		frappe.conn.sql("delete from tabBin")
-		frappe.conn.sql("delete from `tabGL Entry`")
+		frappe.db.sql("delete from `tabStock Ledger Entry`")
+		frappe.db.sql("delete from tabBin")
+		frappe.db.sql("delete from `tabGL Entry`")
 
 	def test_serialized(self):
 		from erpnext.stock.doctype.stock_entry.test_stock_entry import make_serialized_item
@@ -824,9 +824,9 @@
 		si.insert()
 		si.submit()
 		
-		self.assertEquals(frappe.conn.get_value("Serial No", serial_nos[0], "status"), "Delivered")
-		self.assertFalse(frappe.conn.get_value("Serial No", serial_nos[0], "warehouse"))
-		self.assertEquals(frappe.conn.get_value("Serial No", serial_nos[0], 
+		self.assertEquals(frappe.db.get_value("Serial No", serial_nos[0], "status"), "Delivered")
+		self.assertFalse(frappe.db.get_value("Serial No", serial_nos[0], "warehouse"))
+		self.assertEquals(frappe.db.get_value("Serial No", serial_nos[0], 
 			"delivery_document_no"), si.doc.name)
 			
 		return si
@@ -838,9 +838,9 @@
 
 		serial_nos = get_serial_nos(si.doclist[1].serial_no)
 
-		self.assertEquals(frappe.conn.get_value("Serial No", serial_nos[0], "status"), "Available")
-		self.assertEquals(frappe.conn.get_value("Serial No", serial_nos[0], "warehouse"), "_Test Warehouse - _TC")
-		self.assertFalse(frappe.conn.get_value("Serial No", serial_nos[0], 
+		self.assertEquals(frappe.db.get_value("Serial No", serial_nos[0], "status"), "Available")
+		self.assertEquals(frappe.db.get_value("Serial No", serial_nos[0], "warehouse"), "_Test Warehouse - _TC")
+		self.assertFalse(frappe.db.get_value("Serial No", serial_nos[0], 
 			"delivery_document_no"))
 
 	def test_serialize_status(self):
diff --git a/erpnext/accounts/doctype/sales_taxes_and_charges_master/sales_taxes_and_charges_master.py b/erpnext/accounts/doctype/sales_taxes_and_charges_master/sales_taxes_and_charges_master.py
index 6c1a877..047bbd4 100644
--- a/erpnext/accounts/doctype/sales_taxes_and_charges_master/sales_taxes_and_charges_master.py
+++ b/erpnext/accounts/doctype/sales_taxes_and_charges_master/sales_taxes_and_charges_master.py
@@ -9,7 +9,7 @@
 class DocType(DocListController):		
 	def validate(self):
 		if self.doc.is_default == 1:
-			frappe.conn.sql("""update `tabSales Taxes and Charges Master` set is_default = 0 
+			frappe.db.sql("""update `tabSales Taxes and Charges Master` set is_default = 0 
 				where ifnull(is_default,0) = 1 and name != %s and company = %s""", 
 				(self.doc.name, self.doc.company))
 				
diff --git a/erpnext/accounts/general_ledger.py b/erpnext/accounts/general_ledger.py
index d0c8aaf..bfc2d2d 100644
--- a/erpnext/accounts/general_ledger.py
+++ b/erpnext/accounts/general_ledger.py
@@ -90,7 +90,7 @@
 			
 def validate_account_for_auto_accounting_for_stock(gl_map):
 	if gl_map[0].voucher_type=="Journal Voucher":
-		aii_accounts = [d[0] for d in frappe.conn.sql("""select name from tabAccount 
+		aii_accounts = [d[0] for d in frappe.db.sql("""select name from tabAccount 
 			where account_type = 'Warehouse' and ifnull(master_name, '')!=''""")]
 		
 		for entry in gl_map:
@@ -107,12 +107,12 @@
 		check_freezing_date, update_outstanding_amt, validate_frozen_account
 		
 	if not gl_entries:
-		gl_entries = frappe.conn.sql("""select * from `tabGL Entry` 
+		gl_entries = frappe.db.sql("""select * from `tabGL Entry` 
 			where voucher_type=%s and voucher_no=%s""", (voucher_type, voucher_no), as_dict=True)
 	if gl_entries:
 		check_freezing_date(gl_entries[0]["posting_date"], adv_adj)
 	
-	frappe.conn.sql("""delete from `tabGL Entry` where voucher_type=%s and voucher_no=%s""", 
+	frappe.db.sql("""delete from `tabGL Entry` where voucher_type=%s and voucher_no=%s""", 
 		(voucher_type or gl_entries[0]["voucher_type"], voucher_no or gl_entries[0]["voucher_no"]))
 	
 	for entry in gl_entries:
diff --git a/erpnext/accounts/page/accounts_browser/accounts_browser.py b/erpnext/accounts/page/accounts_browser/accounts_browser.py
index 594150c..15cfdd2 100644
--- a/erpnext/accounts/page/accounts_browser/accounts_browser.py
+++ b/erpnext/accounts/page/accounts_browser/accounts_browser.py
@@ -20,7 +20,7 @@
 	
 	# root
 	if args['parent'] in ("Accounts", "Cost Centers"):
-		acc = frappe.conn.sql(""" select 
+		acc = frappe.db.sql(""" select 
 			name as value, if(group_or_ledger='Group', 1, 0) as expandable
 			from `tab%s`
 			where ifnull(parent_%s,'') = ''
@@ -29,7 +29,7 @@
 				company, as_dict=1)
 	else:	
 		# other
-		acc = frappe.conn.sql("""select 
+		acc = frappe.db.sql("""select 
 			name as value, if(group_or_ledger='Group', 1, 0) as expandable
 	 		from `tab%s` 
 			where ifnull(parent_%s,'') = %s
@@ -38,7 +38,7 @@
 				args['parent'], as_dict=1)
 				
 	if ctype == 'Account':
-		currency = frappe.conn.sql("select default_currency from `tabCompany` where name = %s", company)[0][0]
+		currency = frappe.db.sql("select default_currency from `tabCompany` where name = %s", company)[0][0]
 		for each in acc:
 			bal = get_balance_on(each.get("value"))
 			each["currency"] = currency
diff --git a/erpnext/accounts/party.py b/erpnext/accounts/party.py
index 840b111..0e6851a 100644
--- a/erpnext/accounts/party.py
+++ b/erpnext/accounts/party.py
@@ -48,7 +48,7 @@
 def set_address_details(out, party, party_type):
 	billing_address_field = "customer_address" if party_type == "Lead" \
 		else party_type.lower() + "_address"
-	out[billing_address_field] = frappe.conn.get_value("Address", 
+	out[billing_address_field] = frappe.db.get_value("Address", 
 		{party_type.lower(): party.name, "is_primary_address":1}, "name")
 	
 	# address display
@@ -56,12 +56,12 @@
 	
 	# shipping address
 	if party_type in ["Customer", "Lead"]:
-		out.shipping_address_name = frappe.conn.get_value("Address", 
+		out.shipping_address_name = frappe.db.get_value("Address", 
 			{party_type.lower(): party.name, "is_shipping_address":1}, "name")
 		out.shipping_address = get_address_display(out["shipping_address_name"])
 	
 def set_contact_details(out, party, party_type):
-	out.contact_person = frappe.conn.get_value("Contact", 
+	out.contact_person = frappe.db.get_value("Contact", 
 		{party_type.lower(): party.name, "is_primary_contact":1}, "name")
 	
 	out.update(get_contact_details(out.contact_person))
@@ -91,14 +91,14 @@
 		price_list = party.default_price_list
 		
 	if not price_list and party.party_type=="Customer":
-		price_list =  frappe.conn.get_value("Customer Group", 
+		price_list =  frappe.db.get_value("Customer Group", 
 			party.customer_group, "default_price_list")
 
 	if not price_list:
 		price_list = given_price_list
 
 	if price_list:
-		out.price_list_currency = frappe.conn.get_value("Price List", price_list, "currency")
+		out.price_list_currency = frappe.db.get_value("Price List", price_list, "currency")
 		
 	out["selling_price_list" if party.doctype=="Customer" else "buying_price_list"] = price_list
 	
@@ -113,7 +113,7 @@
 	if party:
 		account = get_party_account(company, party, party_type)
 	elif account:
-		party = frappe.conn.get_value('Account', account, 'master_name')
+		party = frappe.db.get_value('Account', account, 'master_name')
 
 	account_fieldname = "debit_to" if party_type=="Customer" else "credit_to" 
 
@@ -129,7 +129,7 @@
 		frappe.throw(_("Please select company first."))
 
 	if party:
-		acc_head = frappe.conn.get_value("Account", {"master_name":party,
+		acc_head = frappe.db.get_value("Account", {"master_name":party,
 			"master_type": party_type, "company": company})
 
 		if not acc_head:
@@ -143,11 +143,11 @@
 	if posting_date:
 		credit_days = 0
 		if account:
-			credit_days = frappe.conn.get_value("Account", account, "credit_days")
+			credit_days = frappe.db.get_value("Account", account, "credit_days")
 		if party and not credit_days:
-			credit_days = frappe.conn.get_value(party_type, party, "credit_days")
+			credit_days = frappe.db.get_value(party_type, party, "credit_days")
 		if company and not credit_days:
-			credit_days = frappe.conn.get_value("Company", company, "credit_days")
+			credit_days = frappe.db.get_value("Company", company, "credit_days")
 			
 		due_date = add_days(posting_date, credit_days) if credit_days else posting_date
 
@@ -157,9 +157,9 @@
 	if not company:
 		frappe.throw(_("Company is required"))
 		
-	company_details = frappe.conn.get_value("Company", company, 
+	company_details = frappe.db.get_value("Company", company, 
 		["abbr", "receivables_group", "payables_group"], as_dict=True)
-	if not frappe.conn.exists("Account", (party + " - " + company_details.abbr)):
+	if not frappe.db.exists("Account", (party + " - " + company_details.abbr)):
 		parent_account = company_details.receivables_group \
 			if party_type=="Customer" else company_details.payables_group
 
diff --git a/erpnext/accounts/report/accounts_payable/accounts_payable.py b/erpnext/accounts/report/accounts_payable/accounts_payable.py
index 57bdf9f..fffc948 100644
--- a/erpnext/accounts/report/accounts_payable/accounts_payable.py
+++ b/erpnext/accounts/report/accounts_payable/accounts_payable.py
@@ -9,10 +9,10 @@
 
 def execute(filters=None):
 	if not filters: filters = {}
-	supplier_naming_by = frappe.conn.get_value("Buying Settings", None, "supp_master_name")
+	supplier_naming_by = frappe.db.get_value("Buying Settings", None, "supp_master_name")
 	columns = get_columns(supplier_naming_by)
 	entries = get_gl_entries(filters)
-	account_map = dict(((r.name, r) for r in frappe.conn.sql("""select acc.name, 
+	account_map = dict(((r.name, r) for r in frappe.db.sql("""select acc.name, 
 		supp.supplier_name, supp.name as supplier 
 		from `tabAccount` acc, `tabSupplier` supp 
 		where acc.master_type="Supplier" and supp.name=acc.master_name""", as_dict=1)))
@@ -85,7 +85,7 @@
 def get_gl_entries(filters, before_report_date=True):
 	conditions, supplier_accounts = get_conditions(filters, before_report_date)
 	gl_entries = []
-	gl_entries = frappe.conn.sql("""select * from `tabGL Entry` 
+	gl_entries = frappe.db.sql("""select * from `tabGL Entry` 
 		where docstatus < 2 %s order by posting_date, account""" % 
 		(conditions), tuple(supplier_accounts), as_dict=1)
 	return gl_entries
@@ -99,7 +99,7 @@
 	if filters.get("account"):
 		supplier_accounts = [filters["account"]]
 	else:
-		supplier_accounts = frappe.conn.sql_list("""select name from `tabAccount` 
+		supplier_accounts = frappe.db.sql_list("""select name from `tabAccount` 
 			where ifnull(master_type, '') = 'Supplier' and docstatus < 2 %s""" % 
 			conditions, filters)
 	
@@ -118,7 +118,7 @@
 	
 def get_account_supplier_type_map():
 	account_supplier_type_map = {}
-	for each in frappe.conn.sql("""select acc.name, supp.supplier_type from `tabSupplier` supp, 
+	for each in frappe.db.sql("""select acc.name, supp.supplier_type from `tabSupplier` supp, 
 			`tabAccount` acc where supp.name = acc.master_name group by acc.name"""):
 		account_supplier_type_map[each[0]] = each[1]
 
@@ -128,14 +128,14 @@
 	voucher_details = {}
 	for dt in ["Purchase Invoice", "Journal Voucher"]:
 		voucher_details.setdefault(dt, frappe._dict())
-		for t in frappe.conn.sql("""select name, due_date, bill_no, bill_date 
+		for t in frappe.db.sql("""select name, due_date, bill_no, bill_date 
 				from `tab%s`""" % dt, as_dict=1):
 			voucher_details[dt].setdefault(t.name, t)
 		
 	return voucher_details
 
 def get_outstanding_amount(gle, report_date):
-	payment_amount = frappe.conn.sql("""
+	payment_amount = frappe.db.sql("""
 		select sum(ifnull(debit, 0)) - sum(ifnull(credit, 0)) 
 		from `tabGL Entry` 
 		where account = %s and posting_date <= %s and against_voucher_type = %s 
diff --git a/erpnext/accounts/report/accounts_receivable/accounts_receivable.py b/erpnext/accounts/report/accounts_receivable/accounts_receivable.py
index 9b2caf0..427669f 100644
--- a/erpnext/accounts/report/accounts_receivable/accounts_receivable.py
+++ b/erpnext/accounts/report/accounts_receivable/accounts_receivable.py
@@ -15,7 +15,7 @@
 			else self.filters.report_date
 			
 	def run(self):
-		customer_naming_by = frappe.conn.get_value("Selling Settings", None, "cust_master_name")
+		customer_naming_by = frappe.db.get_value("Selling Settings", None, "cust_master_name")
 		return self.get_columns(customer_naming_by), self.get_data(customer_naming_by)
 		
 	def get_columns(self, customer_naming_by):
@@ -111,7 +111,7 @@
 		
 	def get_account_map(self):
 		if not hasattr(self, "account_map"):
-			self.account_map = dict(((r.name, r) for r in frappe.conn.sql("""select 
+			self.account_map = dict(((r.name, r) for r in frappe.db.sql("""select 
 				acc.name, cust.name as customer, cust.customer_name, cust.territory
 				from `tabAccount` acc left join `tabCustomer` cust 
 				on cust.name=acc.master_name where acc.master_type="Customer" """, as_dict=True)))
@@ -121,7 +121,7 @@
 	def get_due_date(self, gle):
 		if not hasattr(self, "invoice_due_date_map"):
 			# TODO can be restricted to posting date
-			self.invoice_due_date_map = dict(frappe.conn.sql("""select name, due_date
+			self.invoice_due_date_map = dict(frappe.db.sql("""select name, due_date
 				from `tabSales Invoice` where docstatus=1"""))
 				
 		return gle.voucher_type == "Sales Invoice" \
@@ -130,7 +130,7 @@
 	def get_gl_entries(self):
 		if not hasattr(self, "gl_entries"):
 			conditions, values = self.prepare_conditions()
-			self.gl_entries = frappe.conn.sql("""select * from `tabGL Entry`
+			self.gl_entries = frappe.db.sql("""select * from `tabGL Entry`
 				where docstatus < 2 {0} order by posting_date, account""".format(conditions),
 				values, as_dict=True)
 		return self.gl_entries
diff --git a/erpnext/accounts/report/bank_clearance_summary/bank_clearance_summary.py b/erpnext/accounts/report/bank_clearance_summary/bank_clearance_summary.py
index 1ed3d73..f86c932 100644
--- a/erpnext/accounts/report/bank_clearance_summary/bank_clearance_summary.py
+++ b/erpnext/accounts/report/bank_clearance_summary/bank_clearance_summary.py
@@ -33,7 +33,7 @@
 	
 def get_entries(filters):
 	conditions = get_conditions(filters)
-	entries =  frappe.conn.sql("""select jv.name, jvd.account, jv.posting_date, 
+	entries =  frappe.db.sql("""select jv.name, jvd.account, jv.posting_date, 
 		jv.clearance_date, jvd.against_account, jvd.debit, jvd.credit
 		from `tabJournal Voucher Detail` jvd, `tabJournal Voucher` jv 
 		where jvd.parent = jv.name and jv.docstatus=1 %s
diff --git a/erpnext/accounts/report/bank_reconciliation_statement/bank_reconciliation_statement.py b/erpnext/accounts/report/bank_reconciliation_statement/bank_reconciliation_statement.py
index fed9170..4cb14db 100644
--- a/erpnext/accounts/report/bank_reconciliation_statement/bank_reconciliation_statement.py
+++ b/erpnext/accounts/report/bank_reconciliation_statement/bank_reconciliation_statement.py
@@ -8,7 +8,7 @@
 def execute(filters=None):
 	if not filters: filters = {}
 	
-	debit_or_credit = frappe.conn.get_value("Account", filters["account"], "debit_or_credit")
+	debit_or_credit = frappe.db.get_value("Account", filters["account"], "debit_or_credit")
 	
 	columns = get_columns()
 	data = get_entries(filters)
@@ -41,7 +41,7 @@
 	]
 	
 def get_entries(filters):
-	entries = frappe.conn.sql("""select 
+	entries = frappe.db.sql("""select 
 			jv.name, jv.posting_date, jv.clearance_date, jvd.against_account, jvd.debit, jvd.credit
 		from 
 			`tabJournal Voucher Detail` jvd, `tabJournal Voucher` jv 
diff --git a/erpnext/accounts/report/budget_variance_report/budget_variance_report.py b/erpnext/accounts/report/budget_variance_report/budget_variance_report.py
index 0a7abef..c98d205 100644
--- a/erpnext/accounts/report/budget_variance_report/budget_variance_report.py
+++ b/erpnext/accounts/report/budget_variance_report/budget_variance_report.py
@@ -62,7 +62,7 @@
 
 #Get cost center & target details
 def get_costcenter_target_details(filters):
-	return frappe.conn.sql("""select cc.name, cc.distribution_id, 
+	return frappe.db.sql("""select cc.name, cc.distribution_id, 
 		cc.parent_cost_center, bd.account, bd.budget_allocated 
 		from `tabCost Center` cc, `tabBudget Detail` bd 
 		where bd.parent=cc.name and bd.fiscal_year=%s and 
@@ -73,7 +73,7 @@
 def get_target_distribution_details(filters):
 	target_details = {}
 
-	for d in frappe.conn.sql("""select bd.name, bdd.month, bdd.percentage_allocation  
+	for d in frappe.db.sql("""select bd.name, bdd.month, bdd.percentage_allocation  
 		from `tabBudget Distribution Detail` bdd, `tabBudget Distribution` bd
 		where bdd.parent=bd.name and bd.fiscal_year=%s""", (filters["fiscal_year"]), as_dict=1):
 			target_details.setdefault(d.name, {}).setdefault(d.month, flt(d.percentage_allocation))
@@ -82,7 +82,7 @@
 
 #Get actual details from gl entry
 def get_actual_details(filters):
-	ac_details = frappe.conn.sql("""select gl.account, gl.debit, gl.credit, 
+	ac_details = frappe.db.sql("""select gl.account, gl.debit, gl.credit, 
 		gl.cost_center, MONTHNAME(gl.posting_date) as month_name 
 		from `tabGL Entry` gl, `tabBudget Detail` bd 
 		where gl.fiscal_year=%s and company=%s
diff --git a/erpnext/accounts/report/customer_account_head/customer_account_head.py b/erpnext/accounts/report/customer_account_head/customer_account_head.py
index 34303e5..291d6aa 100644
--- a/erpnext/accounts/report/customer_account_head/customer_account_head.py
+++ b/erpnext/accounts/report/customer_account_head/customer_account_head.py
@@ -8,7 +8,7 @@
 	account_map = get_account_map()
 	columns = get_columns(account_map)
 	data = []
-	customers = frappe.conn.sql("select name from tabCustomer where docstatus < 2")
+	customers = frappe.db.sql("select name from tabCustomer where docstatus < 2")
 	for cust in customers:
 		row = [cust[0]]
 		for company in sorted(account_map):
@@ -18,7 +18,7 @@
 	return columns, data
 
 def get_account_map():
-	accounts = frappe.conn.sql("""select name, company, master_name 
+	accounts = frappe.db.sql("""select name, company, master_name 
 		from `tabAccount` where master_type = 'Customer' 
 		and ifnull(master_name, '') != '' and docstatus < 2""", as_dict=1)
 
diff --git a/erpnext/accounts/report/general_ledger/general_ledger.py b/erpnext/accounts/report/general_ledger/general_ledger.py
index 4cfda3a..e130e29 100644
--- a/erpnext/accounts/report/general_ledger/general_ledger.py
+++ b/erpnext/accounts/report/general_ledger/general_ledger.py
@@ -8,7 +8,7 @@
 
 def execute(filters=None):
 	account_details = {}
-	for acc in frappe.conn.sql("""select name, debit_or_credit, group_or_ledger 
+	for acc in frappe.db.sql("""select name, debit_or_credit, group_or_ledger 
 		from tabAccount""", as_dict=1):
 			account_details.setdefault(acc.name, acc)
 	
@@ -49,7 +49,7 @@
 	group_by_condition = "group by voucher_type, voucher_no, account" \
 		if filters.get("group_by_voucher") else "group by name"
 		
-	gl_entries = frappe.conn.sql("""select posting_date, account, 
+	gl_entries = frappe.db.sql("""select posting_date, account, 
 			sum(ifnull(debit, 0)) as debit, sum(ifnull(credit, 0)) as credit, 
 			voucher_type, voucher_no, cost_center, remarks, is_opening, against 
 		from `tabGL Entry`
@@ -64,7 +64,7 @@
 def get_conditions(filters):
 	conditions = []
 	if filters.get("account"):
-		lft, rgt = frappe.conn.get_value("Account", filters["account"], ["lft", "rgt"])
+		lft, rgt = frappe.db.get_value("Account", filters["account"], ["lft", "rgt"])
 		conditions.append("""account in (select name from tabAccount 
 			where lft>=%s and rgt<=%s and docstatus<2)""" % (lft, rgt))
 	else:
diff --git a/erpnext/accounts/report/gross_profit/gross_profit.py b/erpnext/accounts/report/gross_profit/gross_profit.py
index 6b915d1..1bbf2d1 100644
--- a/erpnext/accounts/report/gross_profit/gross_profit.py
+++ b/erpnext/accounts/report/gross_profit/gross_profit.py
@@ -59,7 +59,7 @@
 	
 	query += " order by item_code desc, warehouse desc, posting_date desc, posting_time desc, name desc"
 	
-	res = frappe.conn.sql(query, filters, as_dict=True)
+	res = frappe.db.sql(query, filters, as_dict=True)
 	
 	out = {}
 	for r in res:
@@ -73,7 +73,7 @@
 def get_item_sales_bom():
 	item_sales_bom = {}
 	
-	for d in frappe.conn.sql("""select parenttype, parent, parent_item,
+	for d in frappe.db.sql("""select parenttype, parent, parent_item,
 		item_code, warehouse, -1*qty as total_qty, parent_detail_docname
 		from `tabPacked Item` where docstatus=1""", as_dict=True):
 		item_sales_bom.setdefault(d.parenttype, frappe._dict()).setdefault(d.parent,
@@ -90,7 +90,7 @@
 	if filters.get("to_date"):
 		conditions += " and posting_date<=%(to_date)s"
 	
-	delivery_note_items = frappe.conn.sql("""select item.parenttype, dn.name, 
+	delivery_note_items = frappe.db.sql("""select item.parenttype, dn.name, 
 		dn.posting_date, dn.posting_time, dn.project_name, 
 		item.item_code, item.item_name, item.description, item.warehouse,
 		item.qty, item.base_rate, item.base_amount, item.name as "item_row",
@@ -99,7 +99,7 @@
 		where item.parent = dn.name and dn.docstatus = 1 %s
 		order by dn.posting_date desc, dn.posting_time desc""" % (conditions,), filters, as_dict=1)
 
-	sales_invoice_items = frappe.conn.sql("""select item.parenttype, si.name, 
+	sales_invoice_items = frappe.db.sql("""select item.parenttype, si.name, 
 		si.posting_date, si.posting_time, si.project_name,
 		item.item_code, item.item_name, item.description, item.warehouse,
 		item.qty, item.base_rate, item.base_amount, item.name as "item_row",
diff --git a/erpnext/accounts/report/item_wise_purchase_register/item_wise_purchase_register.py b/erpnext/accounts/report/item_wise_purchase_register/item_wise_purchase_register.py
index a9bcbba..8e74873 100644
--- a/erpnext/accounts/report/item_wise_purchase_register/item_wise_purchase_register.py
+++ b/erpnext/accounts/report/item_wise_purchase_register/item_wise_purchase_register.py
@@ -57,7 +57,7 @@
 	conditions = get_conditions(filters)
 	match_conditions = frappe.build_match_conditions("Purchase Invoice")
 	
-	return frappe.conn.sql("""select pi_item.parent, pi.posting_date, pi.credit_to, pi.company, 
+	return frappe.db.sql("""select pi_item.parent, pi.posting_date, pi.credit_to, pi.company, 
 		pi.supplier, pi.remarks, pi_item.item_code, pi_item.item_name, pi_item.item_group, 
 		pi_item.project_name, pi_item.purchase_order, pi_item.purchase_receipt, 
 		pi_item.expense_account, pi_item.qty, pi_item.base_rate, pi_item.base_amount, pi.supplier_name
@@ -66,14 +66,14 @@
 		order by pi.posting_date desc, pi_item.item_code desc""" % (conditions, match_conditions), filters, as_dict=1)
 		
 def get_aii_accounts():
-	return dict(frappe.conn.sql("select name, stock_received_but_not_billed from tabCompany"))
+	return dict(frappe.db.sql("select name, stock_received_but_not_billed from tabCompany"))
 	
 def get_tax_accounts(item_list, columns):
 	import json
 	item_tax = {}
 	tax_accounts = []
 	
-	tax_details = frappe.conn.sql("""select parent, account_head, item_wise_tax_detail
+	tax_details = frappe.db.sql("""select parent, account_head, item_wise_tax_detail
 		from `tabPurchase Taxes and Charges` where parenttype = 'Purchase Invoice' 
 		and docstatus = 1 and ifnull(account_head, '') != '' and category in ('Total', 'Valuation and Total') 
 		and parent in (%s)""" % ', '.join(['%s']*len(item_list)), tuple([item.parent for item in item_list]))
diff --git a/erpnext/accounts/report/item_wise_sales_register/item_wise_sales_register.py b/erpnext/accounts/report/item_wise_sales_register/item_wise_sales_register.py
index 421a517..6a0d051 100644
--- a/erpnext/accounts/report/item_wise_sales_register/item_wise_sales_register.py
+++ b/erpnext/accounts/report/item_wise_sales_register/item_wise_sales_register.py
@@ -55,7 +55,7 @@
 		
 def get_items(filters):
 	conditions = get_conditions(filters)
-	return frappe.conn.sql("""select si_item.parent, si.posting_date, si.debit_to, si.project_name, 
+	return frappe.db.sql("""select si_item.parent, si.posting_date, si.debit_to, si.project_name, 
 		si.customer, si.remarks, si.territory, si.company, si_item.item_code, si_item.item_name, 
 		si_item.item_group, si_item.sales_order, si_item.delivery_note, si_item.income_account, 
 		si_item.qty, si_item.base_rate, si_item.base_amount, si.customer_name
@@ -68,7 +68,7 @@
 	item_tax = {}
 	tax_accounts = []
 	
-	tax_details = frappe.conn.sql("""select parent, account_head, item_wise_tax_detail
+	tax_details = frappe.db.sql("""select parent, account_head, item_wise_tax_detail
 		from `tabSales Taxes and Charges` where parenttype = 'Sales Invoice' 
 		and docstatus = 1 and ifnull(account_head, '') != ''
 		and parent in (%s)""" % ', '.join(['%s']*len(item_list)), 
diff --git a/erpnext/accounts/report/payment_period_based_on_invoice_date/payment_period_based_on_invoice_date.py b/erpnext/accounts/report/payment_period_based_on_invoice_date/payment_period_based_on_invoice_date.py
index 5754dd1..36d02e0 100644
--- a/erpnext/accounts/report/payment_period_based_on_invoice_date/payment_period_based_on_invoice_date.py
+++ b/erpnext/accounts/report/payment_period_based_on_invoice_date/payment_period_based_on_invoice_date.py
@@ -58,7 +58,7 @@
 		else:
 			cond += " and master_type = 'Supplier'"
 
-		party_accounts = frappe.conn.sql_list("""select name from `tabAccount` 
+		party_accounts = frappe.db.sql_list("""select name from `tabAccount` 
 			where ifnull(master_name, '')!='' and docstatus < 2 %s""" % cond)
 	
 	if party_accounts:
@@ -74,7 +74,7 @@
 	
 def get_entries(filters):
 	conditions, party_accounts = get_conditions(filters)
-	entries =  frappe.conn.sql("""select jv.name, jvd.account, jv.posting_date, 
+	entries =  frappe.db.sql("""select jv.name, jvd.account, jv.posting_date, 
 		jvd.against_voucher, jvd.against_invoice, jvd.debit, jvd.credit, 
 		jv.cheque_no, jv.cheque_date, jv.remark 
 		from `tabJournal Voucher Detail` jvd, `tabJournal Voucher` jv 
@@ -86,10 +86,10 @@
 def get_invoice_posting_date_map(filters):
 	invoice_posting_date_map = {}
 	if filters.get("payment_type") == "Incoming":
-		for t in frappe.conn.sql("""select name, posting_date from `tabSales Invoice`"""):
+		for t in frappe.db.sql("""select name, posting_date from `tabSales Invoice`"""):
 			invoice_posting_date_map[t[0]] = t[1]
 	else:
-		for t in frappe.conn.sql("""select name, posting_date from `tabPurchase Invoice`"""):
+		for t in frappe.db.sql("""select name, posting_date from `tabPurchase Invoice`"""):
 			invoice_posting_date_map[t[0]] = t[1]
 
 	return invoice_posting_date_map
\ No newline at end of file
diff --git a/erpnext/accounts/report/purchase_register/purchase_register.py b/erpnext/accounts/report/purchase_register/purchase_register.py
index b60b70d..a82ec29 100644
--- a/erpnext/accounts/report/purchase_register/purchase_register.py
+++ b/erpnext/accounts/report/purchase_register/purchase_register.py
@@ -72,12 +72,12 @@
 	expense_accounts = tax_accounts = expense_columns = tax_columns = []
 	
 	if invoice_list:	
-		expense_accounts = frappe.conn.sql_list("""select distinct expense_account 
+		expense_accounts = frappe.db.sql_list("""select distinct expense_account 
 			from `tabPurchase Invoice Item` where docstatus = 1 and ifnull(expense_account, '') != '' 
 			and parent in (%s) order by expense_account""" % 
 			', '.join(['%s']*len(invoice_list)), tuple([inv.name for inv in invoice_list]))
 		
-		tax_accounts = 	frappe.conn.sql_list("""select distinct account_head 
+		tax_accounts = 	frappe.db.sql_list("""select distinct account_head 
 			from `tabPurchase Taxes and Charges` where parenttype = 'Purchase Invoice' 
 			and docstatus = 1 and ifnull(account_head, '') != '' and category in ('Total', 'Valuation and Total') 
 			and parent in (%s) order by account_head""" % 
@@ -109,14 +109,14 @@
 	
 def get_invoices(filters):
 	conditions = get_conditions(filters)
-	return frappe.conn.sql("""select name, posting_date, credit_to, supplier, supplier_name, 
+	return frappe.db.sql("""select name, posting_date, credit_to, supplier, supplier_name, 
 		bill_no, bill_date, remarks, net_total, grand_total, outstanding_amount 
 		from `tabPurchase Invoice` where docstatus = 1 %s 
 		order by posting_date desc, name desc""" % conditions, filters, as_dict=1)
 	
 	
 def get_invoice_expense_map(invoice_list):
-	expense_details = frappe.conn.sql("""select parent, expense_account, sum(base_amount) as amount
+	expense_details = frappe.db.sql("""select parent, expense_account, sum(base_amount) as amount
 		from `tabPurchase Invoice Item` where parent in (%s) group by parent, expense_account""" % 
 		', '.join(['%s']*len(invoice_list)), tuple([inv.name for inv in invoice_list]), as_dict=1)
 	
@@ -128,7 +128,7 @@
 	return invoice_expense_map
 	
 def get_invoice_tax_map(invoice_list, invoice_expense_map, expense_accounts):
-	tax_details = frappe.conn.sql("""select parent, account_head, sum(tax_amount) as tax_amount
+	tax_details = frappe.db.sql("""select parent, account_head, sum(tax_amount) as tax_amount
 		from `tabPurchase Taxes and Charges` where parent in (%s) group by parent, account_head""" % 
 		', '.join(['%s']*len(invoice_list)), tuple([inv.name for inv in invoice_list]), as_dict=1)
 	
@@ -146,7 +146,7 @@
 	return invoice_expense_map, invoice_tax_map
 	
 def get_invoice_po_pr_map(invoice_list):
-	pi_items = frappe.conn.sql("""select parent, purchase_order, purchase_receipt, 
+	pi_items = frappe.db.sql("""select parent, purchase_order, purchase_receipt, 
 		project_name from `tabPurchase Invoice Item` where parent in (%s) 
 		and (ifnull(purchase_order, '') != '' or ifnull(purchase_receipt, '') != '')""" % 
 		', '.join(['%s']*len(invoice_list)), tuple([inv.name for inv in invoice_list]), as_dict=1)
@@ -168,7 +168,7 @@
 def get_account_details(invoice_list):
 	account_map = {}
 	accounts = list(set([inv.credit_to for inv in invoice_list]))
-	for acc in frappe.conn.sql("""select name, parent_account from tabAccount 
+	for acc in frappe.db.sql("""select name, parent_account from tabAccount 
 		where name in (%s)""" % ", ".join(["%s"]*len(accounts)), tuple(accounts), as_dict=1):
 			account_map[acc.name] = acc.parent_account
 						
diff --git a/erpnext/accounts/report/sales_register/sales_register.py b/erpnext/accounts/report/sales_register/sales_register.py
index 23e491d..4131ee2 100644
--- a/erpnext/accounts/report/sales_register/sales_register.py
+++ b/erpnext/accounts/report/sales_register/sales_register.py
@@ -72,12 +72,12 @@
 	income_accounts = tax_accounts = income_columns = tax_columns = []
 	
 	if invoice_list:
-		income_accounts = frappe.conn.sql_list("""select distinct income_account 
+		income_accounts = frappe.db.sql_list("""select distinct income_account 
 			from `tabSales Invoice Item` where docstatus = 1 and parent in (%s) 
 			order by income_account""" % 
 			', '.join(['%s']*len(invoice_list)), tuple([inv.name for inv in invoice_list]))
 	
-		tax_accounts = 	frappe.conn.sql_list("""select distinct account_head 
+		tax_accounts = 	frappe.db.sql_list("""select distinct account_head 
 			from `tabSales Taxes and Charges` where parenttype = 'Sales Invoice' 
 			and docstatus = 1 and ifnull(tax_amount_after_discount_amount, 0) != 0 
 			and parent in (%s) order by account_head""" % 
@@ -107,14 +107,14 @@
 	
 def get_invoices(filters):
 	conditions = get_conditions(filters)
-	return frappe.conn.sql("""select name, posting_date, debit_to, project_name, customer, 
+	return frappe.db.sql("""select name, posting_date, debit_to, project_name, customer, 
 		customer_name, remarks, net_total, grand_total, rounded_total, outstanding_amount 
 		from `tabSales Invoice` 
 		where docstatus = 1 %s order by posting_date desc, name desc""" % 
 		conditions, filters, as_dict=1)
 	
 def get_invoice_income_map(invoice_list):
-	income_details = frappe.conn.sql("""select parent, income_account, sum(base_amount) as amount
+	income_details = frappe.db.sql("""select parent, income_account, sum(base_amount) as amount
 		from `tabSales Invoice Item` where parent in (%s) group by parent, income_account""" % 
 		', '.join(['%s']*len(invoice_list)), tuple([inv.name for inv in invoice_list]), as_dict=1)
 	
@@ -126,7 +126,7 @@
 	return invoice_income_map
 	
 def get_invoice_tax_map(invoice_list, invoice_income_map, income_accounts):
-	tax_details = frappe.conn.sql("""select parent, account_head, 
+	tax_details = frappe.db.sql("""select parent, account_head, 
 		sum(tax_amount_after_discount_amount) as tax_amount 
 		from `tabSales Taxes and Charges` where parent in (%s) group by parent, account_head""" % 
 		', '.join(['%s']*len(invoice_list)), tuple([inv.name for inv in invoice_list]), as_dict=1)
@@ -145,7 +145,7 @@
 	return invoice_income_map, invoice_tax_map
 	
 def get_invoice_so_dn_map(invoice_list):
-	si_items = frappe.conn.sql("""select parent, sales_order, delivery_note
+	si_items = frappe.db.sql("""select parent, sales_order, delivery_note
 		from `tabSales Invoice Item` where parent in (%s) 
 		and (ifnull(sales_order, '') != '' or ifnull(delivery_note, '') != '')""" % 
 		', '.join(['%s']*len(invoice_list)), tuple([inv.name for inv in invoice_list]), as_dict=1)
@@ -164,7 +164,7 @@
 def get_customer_deatils(invoice_list):
 	customer_map = {}
 	customers = list(set([inv.customer for inv in invoice_list]))
-	for cust in frappe.conn.sql("""select name, territory from `tabCustomer` 
+	for cust in frappe.db.sql("""select name, territory from `tabCustomer` 
 		where name in (%s)""" % ", ".join(["%s"]*len(customers)), tuple(customers), as_dict=1):
 			customer_map[cust.name] = cust.territory
 	
@@ -173,7 +173,7 @@
 def get_account_details(invoice_list):
 	account_map = {}
 	accounts = list(set([inv.debit_to for inv in invoice_list]))
-	for acc in frappe.conn.sql("""select name, parent_account from tabAccount 
+	for acc in frappe.db.sql("""select name, parent_account from tabAccount 
 		where name in (%s)""" % ", ".join(["%s"]*len(accounts)), tuple(accounts), as_dict=1):
 			account_map[acc.name] = acc.parent_account
 						
diff --git a/erpnext/accounts/report/supplier_account_head/supplier_account_head.py b/erpnext/accounts/report/supplier_account_head/supplier_account_head.py
index c015462..11e1a0d 100644
--- a/erpnext/accounts/report/supplier_account_head/supplier_account_head.py
+++ b/erpnext/accounts/report/supplier_account_head/supplier_account_head.py
@@ -8,7 +8,7 @@
 	account_map = get_account_map()
 	columns = get_columns(account_map)
 	data = []
-	suppliers = frappe.conn.sql("select name from tabSupplier where docstatus < 2")
+	suppliers = frappe.db.sql("select name from tabSupplier where docstatus < 2")
 	for supplier in suppliers:
 		row = [supplier[0]]
 		for company in sorted(account_map):
@@ -18,7 +18,7 @@
 	return columns, data
 
 def get_account_map():
-	accounts = frappe.conn.sql("""select name, company, master_name 
+	accounts = frappe.db.sql("""select name, company, master_name 
 		from `tabAccount` where master_type = 'Supplier' 
 		and ifnull(master_name, '') != '' and docstatus < 2""", as_dict=1)
 
diff --git a/erpnext/accounts/utils.py b/erpnext/accounts/utils.py
index 1a5af8e..4edf774 100644
--- a/erpnext/accounts/utils.py
+++ b/erpnext/accounts/utils.py
@@ -26,7 +26,7 @@
 	else:
 		cond = "'%s' >= year_start_date and '%s' <= year_end_date" % \
 			(date, date)
-	fy = frappe.conn.sql("""select name, year_start_date, year_end_date
+	fy = frappe.db.sql("""select name, year_start_date, year_end_date
 		from `tabFiscal Year` where %s order by year_start_date desc""" % cond)
 	
 	if not fy:
@@ -73,7 +73,7 @@
 			# hence, assuming balance as 0.0
 			return 0.0
 		
-	acc = frappe.conn.get_value('Account', account, \
+	acc = frappe.db.get_value('Account', account, \
 		['lft', 'rgt', 'debit_or_credit', 'is_pl_account', 'group_or_ledger'], as_dict=1)
 	
 	# for pl accounts, get balance within a fiscal year
@@ -90,7 +90,7 @@
 	else:
 		cond.append("""gle.account = "%s" """ % (account, ))
 	
-	bal = frappe.conn.sql("""
+	bal = frappe.db.sql("""
 		SELECT sum(ifnull(debit, 0)) - sum(ifnull(credit, 0)) 
 		FROM `tabGL Entry` gle
 		WHERE %s""" % " and ".join(cond))[0][0]
@@ -160,7 +160,7 @@
 		check if amount is same
 		check if jv is submitted
 	"""
-	ret = frappe.conn.sql("""
+	ret = frappe.db.sql("""
 		select t2.%(dr_or_cr)s from `tabJournal Voucher` t1, `tabJournal Voucher Detail` t2 
 		where t1.name = t2.parent and t2.account = '%(account)s' 
 		and ifnull(t2.against_voucher, '')='' 
@@ -176,14 +176,14 @@
 		Updates against document, if partial amount splits into rows
 	"""
 
-	frappe.conn.sql("""
+	frappe.db.sql("""
 		update `tabJournal Voucher Detail` t1, `tabJournal Voucher` t2	
 		set t1.%(dr_or_cr)s = '%(allocated_amt)s', 
 		t1.%(against_fld)s = '%(against_voucher)s', t2.modified = now() 
 		where t1.name = '%(voucher_detail_no)s' and t1.parent = t2.name""" % d)
 	
 	if d['allocated_amt'] < d['unadjusted_amt']:
-		jvd = frappe.conn.sql("""select cost_center, balance, against_account, is_advance 
+		jvd = frappe.db.sql("""select cost_center, balance, against_account, is_advance 
 			from `tabJournal Voucher Detail` where name = %s""", d['voucher_detail_no'])
 		# new entry with balance amount
 		ch = addchild(jv_obj.doc, 'entries', 'Journal Voucher Detail')
@@ -203,7 +203,7 @@
 
 	conditions, filter_values = build_filter_conditions(filters)
 		
-	return frappe.conn.sql("""select name, parent_account from `tabAccount` 
+	return frappe.db.sql("""select name, parent_account from `tabAccount` 
 		where docstatus < 2 %s and %s like %s order by name limit %s, %s""" % 
 		(conditions, searchfield, "%s", "%s", "%s"), 
 		tuple(filter_values + ["%%%s%%" % txt, start, page_len]))
@@ -214,22 +214,22 @@
 
 	conditions, filter_values = build_filter_conditions(filters)
 	
-	return frappe.conn.sql("""select name, parent_cost_center from `tabCost Center` 
+	return frappe.db.sql("""select name, parent_cost_center from `tabCost Center` 
 		where docstatus < 2 %s and %s like %s order by name limit %s, %s""" % 
 		(conditions, searchfield, "%s", "%s", "%s"), 
 		tuple(filter_values + ["%%%s%%" % txt, start, page_len]))
 		
 def remove_against_link_from_jv(ref_type, ref_no, against_field):
-	linked_jv = frappe.conn.sql_list("""select parent from `tabJournal Voucher Detail` 
+	linked_jv = frappe.db.sql_list("""select parent from `tabJournal Voucher Detail` 
 		where `%s`=%s and docstatus < 2""" % (against_field, "%s"), (ref_no))
 		
 	if linked_jv:	
-		frappe.conn.sql("""update `tabJournal Voucher Detail` set `%s`=null,
+		frappe.db.sql("""update `tabJournal Voucher Detail` set `%s`=null,
 			modified=%s, modified_by=%s
 			where `%s`=%s and docstatus < 2""" % (against_field, "%s", "%s", against_field, "%s"), 
 			(now(), frappe.session.user, ref_no))
 	
-		frappe.conn.sql("""update `tabGL Entry`
+		frappe.db.sql("""update `tabGL Entry`
 			set against_voucher_type=null, against_voucher=null,
 			modified=%s, modified_by=%s
 			where against_voucher_type=%s and against_voucher=%s
@@ -243,7 +243,7 @@
 
 @frappe.whitelist()
 def get_company_default(company, fieldname):
-	value = frappe.conn.get_value("Company", company, fieldname)
+	value = frappe.db.get_value("Company", company, fieldname)
 	
 	if not value:
 		throw(_("Please mention default value for '") + 
@@ -253,7 +253,7 @@
 	return value
 
 def fix_total_debit_credit():
-	vouchers = frappe.conn.sql("""select voucher_type, voucher_no, 
+	vouchers = frappe.db.sql("""select voucher_type, voucher_no, 
 		sum(debit) - sum(credit) as diff 
 		from `tabGL Entry` 
 		group by voucher_type, voucher_no
@@ -263,7 +263,7 @@
 		if abs(d.diff) > 0:
 			dr_or_cr = d.voucher_type == "Sales Invoice" and "credit" or "debit"
 			
-			frappe.conn.sql("""update `tabGL Entry` set %s = %s + %s
+			frappe.db.sql("""update `tabGL Entry` set %s = %s + %s
 				where voucher_type = %s and voucher_no = %s and %s > 0 limit 1""" %
 				(dr_or_cr, dr_or_cr, '%s', '%s', '%s', dr_or_cr), 
 				(d.diff, d.voucher_type, d.voucher_no))
@@ -275,7 +275,7 @@
 	
 	difference = {}
 	
-	account_warehouse = dict(frappe.conn.sql("""select name, master_name from tabAccount 
+	account_warehouse = dict(frappe.db.sql("""select name, master_name from tabAccount 
 		where account_type = 'Warehouse' and ifnull(master_name, '') != '' 
 		and name in (%s)""" % ', '.join(['%s']*len(account_list)), account_list))
 			
@@ -289,16 +289,16 @@
 
 def validate_expense_against_budget(args):
 	args = frappe._dict(args)
-	if frappe.conn.get_value("Account", {"name": args.account, "is_pl_account": "Yes", 
+	if frappe.db.get_value("Account", {"name": args.account, "is_pl_account": "Yes", 
 		"debit_or_credit": "Debit"}):
-			budget = frappe.conn.sql("""
+			budget = frappe.db.sql("""
 				select bd.budget_allocated, cc.distribution_id 
 				from `tabCost Center` cc, `tabBudget Detail` bd
 				where cc.name=bd.parent and cc.name=%s and account=%s and bd.fiscal_year=%s
 			""", (args.cost_center, args.account, args.fiscal_year), as_dict=True)
 			
 			if budget and budget[0].budget_allocated:
-				yearly_action, monthly_action = frappe.conn.get_value("Company", args.company, 
+				yearly_action, monthly_action = frappe.db.get_value("Company", args.company, 
 					["yearly_bgt_flag", "monthly_bgt_flag"])
 				action_for = action = ""
 
@@ -306,7 +306,7 @@
 					budget_amount = get_allocated_budget(budget[0].distribution_id, 
 						args.posting_date, args.fiscal_year, budget[0].budget_allocated)
 					
-					args["month_end_date"] = frappe.conn.sql("select LAST_DAY(%s)", 
+					args["month_end_date"] = frappe.db.sql("select LAST_DAY(%s)", 
 						args.posting_date)[0][0]
 					action_for, action = "Monthly", monthly_action
 					
@@ -326,12 +326,12 @@
 def get_allocated_budget(distribution_id, posting_date, fiscal_year, yearly_budget):
 	if distribution_id:
 		distribution = {}
-		for d in frappe.conn.sql("""select bdd.month, bdd.percentage_allocation 
+		for d in frappe.db.sql("""select bdd.month, bdd.percentage_allocation 
 			from `tabBudget Distribution Detail` bdd, `tabBudget Distribution` bd
 			where bdd.parent=bd.name and bd.fiscal_year=%s""", fiscal_year, as_dict=1):
 				distribution.setdefault(d.month, d.percentage_allocation)
 
-	dt = frappe.conn.get_value("Fiscal Year", fiscal_year, "year_start_date")
+	dt = frappe.db.get_value("Fiscal Year", fiscal_year, "year_start_date")
 	budget_percentage = 0.0
 	
 	while(dt <= getdate(posting_date)):
@@ -348,7 +348,7 @@
 	args["condition"] = " and posting_date<='%s'" % args.month_end_date \
 		if args.get("month_end_date") else ""
 		
-	return frappe.conn.sql("""
+	return frappe.db.sql("""
 		select sum(ifnull(debit, 0)) - sum(ifnull(credit, 0))
 		from `tabGL Entry`
 		where account='%(account)s' and cost_center='%(cost_center)s' 
@@ -367,7 +367,7 @@
 			new_account = frappe.rename_doc("Account", old_account, 
 				existing_new_account or newdn, merge=True if existing_new_account else False)
 
-		frappe.conn.set_value("Account", new_account or old_account, "master_name", newdn)
+		frappe.db.set_value("Account", new_account or old_account, "master_name", newdn)
 		
 def add_abbr_if_missing(dn, company):
 	from erpnext.setup.doctype.company.company import get_name_with_abbr
@@ -379,14 +379,14 @@
 	elif account_for_doctype == "Warehouse":
 		account_for_field = "account_type"
 		
-	return frappe.conn.get_value("Account", {account_for_field: account_for_doctype, 
+	return frappe.db.get_value("Account", {account_for_field: account_for_doctype, 
 		"master_name": account_for})
 		
 def get_currency_precision(currency=None):
 	if not currency:
-		currency = frappe.conn.get_value("Company", 
-			frappe.conn.get_default("company"), "default_currency")
-	currency_format = frappe.conn.get_value("Currency", currency, "number_format")
+		currency = frappe.db.get_value("Company", 
+			frappe.db.get_default("company"), "default_currency")
+	currency_format = frappe.db.get_value("Currency", currency, "number_format")
 	
 	from frappe.utils import get_number_format_info
 	return get_number_format_info(currency_format)[2]