Saturday, October 19, 2019

SQLite SELECT Query

In SQLite database, SELECT statement is used to fetch data from a table. When we create a table and insert some data into that, we have to fetch the data whenever we require. That's why select query is used.
Syntax:
  1. SELECT column1, column2, columnN FROM table_name;   
Here, column1, column2...are the fields of a table, which values you have to fetch. If you want to fetch all the fields available in the field then you can use following syntax:

  1. SELECT * FROM table_name;   
Let's see an example:
  1. SELECT * FROM STUDENT;  
SQLite Select query 1

SQLite Insert Query

In SQLite, INSERT INTO statement is used to add new rows of data into a table. After creating the table, this command is used to insert data into the table.
There are two types of basic syntaxes for INSERT INTO statement:

Syntax1:

  1. INSERT INTO TABLE_NAME [(column1, column2, column3,...columnN)]    
  2. VALUES (value1, value2, value3,...valueN);   
Here, column1, column2, column3,...columnN specifies the name of the columns in the table into which you have to insert data.
You don't need to specify the columns name in the SQlite query if you are adding values to all the columns in the table. But you should make sure that the order of the values is in the same order of the columns in the table.
Then the syntax will be like this:
Syntax2:
  1. INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);   
Let's take an example to demonstrate the INSERT query in SQLite database.
We have already created a table named "STUDENT". Now enter some records in that table.
Inserting values by first method:
  1. INSERT INTO STUDENT (ID,NAME,AGE,ADDRESS,FEES)  
  2. VALUES (1, 'Ajeet', 27, 'Delhi', 20000.00);  
  3. INSERT INTO STUDENT (ID,NAME,AGE,ADDRESS,FEES)  
  4. VALUES (2, 'Akash', 25, 'Patna', 15000.00 );  
  5. INSERT INTO STUDENT (ID,NAME,AGE,ADDRESS,FEES)  
  6. VALUES (3, 'Mark', 23, 'USA', 2000.00 );  
  7. INSERT INTO STUDENT (ID,NAME,AGE,ADDRESS,FEES)  
  8. VALUES (4, 'Chandan', 25, 'Banglore', 65000.00 );  
  9. INSERT INTO STUDENT (ID,NAME,AGE,ADDRESS,FEES)  
  10. VALUES (5, 'Kunwar', 26, 'Agra', 25000.00 );  
SQLite Insert query 1
Second Method:
You can also insert the data into the table by second method.
  1. INSERT INTO STUDENT VALUES (6, 'Kanchan', 21, 'Meerut', 10000.00 );  
SQLite Insert query 2
Output:
You can see the output by using the SELECT statement:
  1. SELECT * FROM STUDENT;  
SQLite Insert query 3

Monday, October 14, 2019

How to Installation SQLite

SQLite is famous for its great feature zero-configuration, which means no complex setup or administration is needed. This chapter will take you through the process of setting up SQLite on Windows, Linux and Mac OS X.

Install SQLite on Windows

  • Step 1 − Go to SQLite download page, and download precompiled binaries from Windows section.
  • Step 2 − Download sqlite-shell-win32-*.zip and sqlite-dll-win32-*.zip zipped files.
  • Step 3 − Create a folder C:\>sqlite and unzip above two zipped files in this folder, which will give you sqlite3.def, sqlite3.dll and sqlite3.exe files.
  • Step 4 − Add C:\>sqlite in your PATH environment variable and finally go to the command prompt and issue sqlite3 command, which should display the following result.
C:\>sqlite3
SQLite version 3.7.15.2 2013-01-09 11:53:05
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite>

Install SQLite on Linux

Today, almost all the flavours of Linux OS are being shipped with SQLite. So you just issue the following command to check if you already have SQLite installed on your machine.
$sqlite3
SQLite version 3.7.15.2 2013-01-09 11:53:05
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite>
If you do not see the above result, then it means you do not have SQLite installed on your Linux machine. Following are the following steps to install SQLite −
  • Step 1 − Go to SQLite download page and download sqlite-autoconf-*.tar.gz from source code section.
  • Step 2 − Run the following command −
$tar xvfz sqlite-autoconf-3071502.tar.gz
$cd sqlite-autoconf-3071502
$./configure --prefix=/usr/local
$make
$make install
The above command will end with SQLite installation on your Linux machine. Which you can verify as explained above.

Install SQLite on Mac OS X

Though the latest version of Mac OS X comes pre-installed with SQLite but if you do not have installation available then just follow these following steps −
  • Step 1 − Go to SQLite download page, and download sqlite-autoconf-*.tar.gz from source code section.
  • Step 2 − Run the following command −
$tar xvfz sqlite-autoconf-3071502.tar.gz
$cd sqlite-autoconf-3071502
$./configure --prefix=/usr/local
$make
$make install
The above procedure will end with SQLite installation on your Mac OS X machine. Which you can verify by issuing the following command −
$sqlite3
SQLite version 3.7.15.2 2013-01-09 11:53:05
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite>
Finally, you have SQLite command prompt where you can issue SQLite commands for your exercises.

SQLite Features/ Why to use SQLite

Following is a list of features which makes SQLite popular among other lightweight databases:
  • SQLite is totally free: SQLite is open-source. So, no license is required to work with it.
  • SQLite is serverless: SQLite doesn't require a different server process or system to operate.
  • SQLite is very flexible: It facilitates you to work on multiple databases on the same session on the same time.
  • Configuration Not Required: SQLite doesn't require configuration. No setup or administration required.
  • SQLite is a cross-platform DBMS: You don't need a large range of different platforms like Windows, Mac OS, Linux, and Unix. It can also be used on a lot of embedded operating systems like Symbian, and Windows CE.
  • Storing data is easy: SQLite provides an efficient way to store data.
  • Variable length of columns: The length of the columns is variable and is not fixed. It facilitates you to allocate only the space a field needs. For example, if you have a varchar(200) column, and you put a 10 characters' length value on it, then SQLite will allocate only 20 characters' space for that value not the whole 200 space.
  • Provide large number of API's: SQLite provides API for a large range of programming languages. For example: .Net languages (Visual Basic, C#), PHP, Java, Objective C, Python and a lot of other programming language.
  • SQLite is written in ANSI-C and provides simple and easy-to-use API.
  • SQLite is available on UNIX (Linux, Mac OS-X, Android, iOS) and Windows (Win32, WinCE, WinRT).

What are difference between SQL vs SQLite?

Differences between SQL and SQLite

SQLSQLite
SQL is a Structured Query Language used to query a Relational Database System. It is written in C language.SQLite is an Embeddable Relational Database Management System which is written in ANSI-C.
SQL is a standard which specifies how a relational schema is created, data is inserted or updated in the relations, transactions are started and stopped, etc.SQLite is file-based. It is different from other SQL databases because unlike most other SQL databases, SQLite does not have a separate server process.
Main components of SQL are Data Definition Language(DDL) , Data Manipulation Language(DML), Embedded SQL and Dynamic SQL.SQLite supports many features of SQL and has high performance and does not support stored procedures.
SQL is Structured Query Language which is used with databases like MySQL, Oracle, Microsoft SQL Server, IBM DB2, etc. It is not a database itself.SQLite is a portable database resource. You have to get an extension of SQLite in whatever language you are programming in to access that database. You can access all of the desktop and mobile applications.
A conventional SQL database needs to be running as a service like OracleDB to connect to and provide a lot of functionalities.SQLite database system doesn?t provide such functionalities.
SQL is a query language which is used by different SQL databases. It is not a database itself.SQLite is a database management system itself which uses SQL.

What is SQLite?

What is SQLite?

SQLite is an in-process library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine. It is a database, which is zero-configured, which means like other databases you do not need to configure it in your system.
SQLite engine is not a standalone process like other databases, you can link it statically or dynamically as per your requirement with your application. SQLite accesses its storage files directly.

Why SQLite?

  • SQLite does not require a separate server process or system to operate (serverless).
  • SQLite comes with zero-configuration, which means no setup or administration needed.
  • A complete SQLite database is stored in a single cross-platform disk file.
  • SQLite is very small and light weight, less than 400KiB fully configured or less than 250KiB with optional features omitted.
  • SQLite is self-contained, which means no external dependencies.
  • SQLite transactions are fully ACID-compliant, allowing safe access from multiple processes or threads.
  • SQLite supports most of the query language features found in SQL92 (SQL2) standard.
  • SQLite is written in ANSI-C and provides simple and easy-to-use API.
  • SQLite is available on UNIX (Linux, Mac OS-X, Android, iOS) and Windows (Win32, WinCE, WinRT).

SQLite A Brief History

  • 2000 - D. Richard Hipp designed SQLite for the purpose of no administration required for operating a program.
  • 2000 - In August, SQLite 1.0 released with GNU Database Manager.
  • 2011 - Hipp announced to add UNQl interface to SQLite DB and to develop UNQLite (Document oriented database).

SQLite Limitations

There are few unsupported features of SQL92 in SQLite which are listed in the following table.
Sr.No.Feature & Description
1
RIGHT OUTER JOIN
Only LEFT OUTER JOIN is implemented.
2
FULL OUTER JOIN
Only LEFT OUTER JOIN is implemented.
3
ALTER TABLE
The RENAME TABLE and ADD COLUMN variants of the ALTER TABLE command are supported. The DROP COLUMN, ALTER COLUMN, ADD CONSTRAINT are not supported.
4
Trigger support
FOR EACH ROW triggers are supported but not FOR EACH STATEMENT triggers.
5
VIEWs
VIEWs in SQLite are read-only. You may not execute a DELETE, INSERT, or UPDATE statement on a view.
6
GRANT and REVOKE
The only access permissions that can be applied are the normal file access permissions of the underlying operating system.

SQLite Commands

The standard SQLite commands to interact with relational databases are similar to SQL. They are CREATE, SELECT, INSERT, UPDATE, DELETE and DROP. These commands can be classified into groups based on their operational nature −

DDL - Data Definition Language

Sr.No.Command & Description
1
CREATE
Creates a new table, a view of a table, or other object in database.
2
ALTER
Modifies an existing database object, such as a table.
3
DROP
Deletes an entire table, a view of a table or other object in the database.

DML - Data Manipulation Language

Sr.No.Command & Description
1
INSERT
Creates a record
2
UPDATE
Modifies records
3
DELETE
Deletes records

DQL - Data Query Language

Sr.No.Command & Description
1
SELECT
Retrieves certain records from one or more tables

iOS SQLite Database

iOS SQLite Database in Swift

SQLite is a Relational Database Management System and we can use SQLite is the type of Embedded file in our iOS applications because it will available as a library. For SQLite there is no stand-alone server running in the background like SQL server, Oracle or MySQL server. We have to handle all the operations within the app through various functions provided by SQLite library.

Now we will see how to use SQLite database in iOS swift applications with example.

Create iOS SQLite App in Swift

To create new project in iOS open Xcode from /Applications folder directory. Once we open Xcode the welcome window will open like as shown below. In welcome window click on the second option “Create a new Xcode Project” or choose File à New à Project.

Xcode application to create ios project

After selecting “Create a new Xcode project” a new window will open in that we need to choose template.

The new Xcode window will contain several built-in app templates to implement common type of iOS apps like page based apps, tab-based apps, games, table-view apps, etc. These templates are having pre-configured interface and source code files. 

For this iOS SQLite example, we will use most basic template “Single View Application”. To select this one, Go to the iOS section in left side à select Application à In main area of dialog select “Single View Application” and then click on next button like as shown below.

Select single view application from ios xcode templates

After click Next we will get window like as shown below, in this we need to mention project name and other details for our application.

Product Name: “SQLite Database with iOS Swift”

The name whatever we enter in Product Name section will be used for the project and app.

Organization Name: “Tutlane”

You can enter the name of your organization or your own name or you can leave it as blank.

Organization Identifier: “com.developersociety”

Enter your organization identifier in case if you don't have any organization identifier enter com.example.

Bundle Identifier: This value will generate automatically based on the values we entered in Product Name and Organization Identifier.

Language: “Swift”

Select language type as “Swift” because we are going to develop applications using swift.

Devices: “Universal”

Choose Devices options as Universal it means that one application is for all apple devices in case if you have any specific requirement to run app only for iPad then you can choose the iPad option to make your application restricted to run only on iPad devices.

Use Core Data: Unselected

This option is used for database operations. In case if you have any database related operations in your application select this option otherwise unselect the option.

Include Unit Tests: Unselected

In case if you need unit tests for your application then select this option otherwise unselect it.

Include UI Tests: Unselected

In case if you need UI tests for your application then select this option otherwise unselect it.

Once you finished entering all the options then click on Next button like as shown below.

Create ios sqlite database app in swift using xcode

Once we click on Next button new dialog will open in that we need to select the location to save our project. Once you select the location to save project then click on Create button like as shown below.

Give path to save new ios application in xcode

After click on Create button the Xcode will create and open a new project. In our project Main.storyboard and ViewController.swift are the main files which we used to design app user interface and to maintain source code.

Main.storyboard - Its visual interface editor and we will use this file to design our app user interface.

ViewController.swift - It contains source code of our application and we use this file to write any code related to our app.

Now in project select Main.storyboard file the Xcode will open visual interface editor like as shown below.

ios sqlite database app storyboard file in xcode

Now select ViewController.swift file in your project that view will be like as shown below.

ios sqlite database app viewcontroller.swift file in xcode

Now we will add Navigation controller to Viewcontroller in storyboard file for that go to Main.storyboard file click on ViewController à Go to Editor à Embed In à Click on Navigation Controller like as shown below

ios sqlite database embed navigation controller in view controller

Add iOS UI Controls to View in Swift

Now we will add controls to our application for that open Object Library. The Object Library will appear at the bottom of Xcode in right side. In case if you don't find Object library, click on the button which is at the third position from the left in the library selector bar like as shown below. (Alternatively you can choose View à Utilities à Show Object Library.)

Object Library in Xcode Application to Search for UI Controls

As we discussed our user interface will be in Main.storyboard file so open Main.storyboard file. Now in Object library search for Table View in Filter field then drag and drop Table View into Main.storyboard ViewController like as shown below.

ios sqlite database app add tableview controller to view controller

Now we will change table view Prototype cell property for that click on table view you will see Prototype cells property in right side and set Prototype cells to “1” like as shown below.

ios sqlite database app change prototype cell values

Now drag three labels and one button and give the title name “Employee Name” and give the name “Edit” and “Delete”.

ios sqlite database app add label controls to viewcontroller

Now click on table view cell and set identifier name as “cell” like as shown below

ios sqlite database app change identifier name

Now search for ViewController in object library filter filed then drag and drop ViewController into Main.storyboard file like as shown below.

ios sqlite database app add new view controller

Now click on title bar of newly added ViewController to change the text and if you want to change the color of background Bar then you can easily select the background color and change it like as shown below.

ios sqlite database app change title and background color of bar

Now in our new Third ViewController drag and drop two labelstext fields and one button control like as shown below

ios sqlite database app add controls to viewcontroller

Now our Main.storyboard file will contain three Controllers like as shown below

ios sqlite database app main.stroyboard file structure after adding controls

Now we will make connection between insert button in first viewcontroller and third viewcontroller for that press Ctrl button in keyboard then drag insert button into third ViewController and give the identifier name as “insertSegue” like as shown below.

ios sqlite database app change connection name

Follow the same step for Edit button and give the segue identifier “editSegue”.

ios sqlite database app edit connection between controllers

Now go to File option à then click on New à then click on File button like as shown below.

ios tableview custom cell add new file in application

Now choose “Cocoa Touch Class” and click on Next button like as shown below.

Add new class cocoa touch class in ios tableview controller

Give the class name and extend with subclass “UITABLEVIEWCELL” and set the language swift. Now click on Next button to create new class file like as shown below.

ios sqlite database studentcell class with uitableviewcell subclass

Now click on Table View Cell and attach the class “StudentCell” like as shown below.

ios sqlite database app assign new studentcell class file

Connect iOS UI Controls to Code in Swift

Now we will make connection between controls and ViewController.swift code for that click on assistant button (overlap circle) in Xcode toolbar right side corner like as shown below

Assistant Editor in iOS Xcode to Mapp Controls with Code

To map the controls, press Ctrl button in keyboard and drag editdelete buttons and table view from view controller and drop into ViewController.swift file like as shown below

ios sqlite database app map controls to viewcontroller.swift file in xcode

Now click on project go to Build Phases à Click on “Link Binary with Libraries” à Click on “+” and add the “libsqlite3.0.tbd” like as shown below.

ios sqlite database app add new sqlite library to application

Once we done all the settings we need to write custom code in ViewController.swift file like as shown below

import UIKit

class ViewController: UIViewControllerUITableViewDataSourceUITableViewDelegate {
var marrStudentData : NSMutableArray!
@IBOutlet weak var tbStudentData: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewWillAppear(animated: Bool) {
self.getStudentData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: Other methods
func getStudentData()
{
marrStudentData = NSMutableArray()
marrStudentData = ModelManager.getInstance().getAllStudentData()
tbStudentData.reloadData()
}
//MARK: UITableView delegate methods
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return marrStudentData.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:StudentCell = tableView.dequeueReusableCellWithIdentifier("cell"asStudentCell
let student:StudentInfo = marrStudentData.objectAtIndex(indexPath.rowasStudentInfo
cell.lblContent.text = "Name : \(student.Name)  \n  Marks : \(student.Marks)"
cell.btnDelete.tag = indexPath.row
cell.btnEdit.tag = indexPath.row
return cell
}
//MARK: UIButton Action methods
@IBAction func btnDeleteClicked(sender: AnyObject) {
let btnDelete : UIButton = sender asUIButton
let selectedIndex : Int = btnDelete.tag
let studentInfo: StudentInfo = marrStudentData.objectAtIndex(selectedIndex) asStudentInfo
let isDeleted = ModelManager.getInstance().deleteStudentData(studentInfo)
if isDeleted {
Util.invokeAlertMethod("", strBody: "Record deleted successfully.", delegate: nil)
else {
Util.invokeAlertMethod("", strBody: "Error in deleting record.", delegate: nil)
}
self.getStudentData()
}
@IBAction func btnEditClicked(sender: AnyObject)
{
self.performSegueWithIdentifier("editSegue", sender: sender)
}
//MARK: Navigation methods
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if(segue.identifier == "editSegue")
{
let btnEdit : UIButton = sender asUIButton
let selectedIndex : Int = btnEdit.tag
let viewController : InsertRecordViewController = segue.destinationViewControllerasInsertRecordViewController
viewController.isEdit = true
viewController.studentData = marrStudentData.objectAtIndex(selectedIndex) asStudentInfo
}
}
}
Now go to File option à then click on New à then click on file option like as shown below

ios tableview custom cell add new file in application'
Now choose “Cocoa Touch Class” and click on Next button like as shown below.

Add new class cocoa touch class in ios tableview controller

Give the class name and extend with subclass “UIViewController” and set the language swift and click on next button to create new class file.

ios sqlite database app create new class

Now embed newly created class to third View Controller like as shown below.

ios sqlite database app map class file to prototype

Open the third viewcontroller in Assistant mode by click on overlap circle icon at top right side and make connection between text fields and the button like as shown below.

ios sqlite database app map controls to viewcontroller.swift file in xcode

Once we done our settings our InsertRecordViewController.swift file should contain code like as shown below.

import UIKit

class InsertRecordViewController: UIViewController {
@IBOutlet weak var FirstName: UITextField!
@IBOutlet weak var LastName: UITextField!
var isEdit : Bool = false
var employeeData : StudentInfo!
override func viewDidLoad() {
super.viewDidLoad()
if(isEdit)
{
FirstName.text = studentData.Name;
LastName.text = studentData.Marks;
}
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: UIButton Action methods
@IBAction func btnBackClicked(sender: AnyObject)
{
self.navigationController?.popViewControllerAnimated(true)
}
@IBAction func btnSaveClicked(sender: AnyObject)
{
if(FirstName.text == "")
{
Util.invokeAlertMethod("", strBody: "Please enter student name.", delegate: nil)
}
else if(LastName.text == "")
{
Util.invokeAlertMethod("", strBody: "Please enter student marks.", delegate: nil)
}
else
{
if(isEdit)
{
let studentInfo: StudentInfo = StudentInfo()
studentInfo.RollNo = studentData.RollNo
studentInfo.Name = FirstName.text!
studentInfo.Marks = LastName.text!
let isUpdated = ModelManager.getInstance().updateStudentData(studentInfo)
if isUpdated {
Util.invokeAlertMethod("", strBody: "Record updated successfully.", delegate: nil)
else {
Util.invokeAlertMethod("", strBody: "Error in updating record.", delegate: nil)
}
}
else
{
let studentInfo: StudentInfo = StudentInfo()
studentInfo.Name = FirstName.text!
studentInfo.Marks = LastName.text!
let isInserted = ModelManager.getInstance().addStudentData(studentInfo)
if isInserted {
Util.invokeAlertMethod("", strBody: "Record Inserted successfully.", delegate: nil)
else {
Util.invokeAlertMethod("", strBody: "Error in inserting record.", delegate: nil)
}
}
self.navigationController?.popViewControllerAnimated(true)
}
}
}
Now go to File option à then click on New à then click on File option like as shown below.

ios tableview custom cell add new file in application

Now choose “Swift Class” and click on Next button like as shown below.

Add swift file in ios sqlite database application

Give name as “Model Manager” and click on create button like as shown below. 

Give model manager to add new swift file in ios sqlite database app

We need to write custom code in ModelManager.swift file to use SQLite database in our applications like as shown below

import UIKit

let sharedInstance = ModelManager()
class ModelManager: NSObject {
var database: FMDatabase? = nil
class func getInstance() -> ModelManager
{
if(sharedInstance.database == nil)
{
sharedInstance.database = FMDatabase(path: Util.getPath("Student.sqlite"))
}
return sharedInstance
}
func addStudentData(studentInfo: StudentInfo) -> Bool {
sharedInstance.database!.open()
let isInserted = sharedInstance.database!.executeUpdate("INSERT INTO student_info (Name, Marks) VALUES (?, ?)", withArgumentsInArray: [studentInfo.Name, studentInfo.Marks])
sharedInstance.database!.close()
return isInserted
}
func updateStudentData(studentInfo: StudentInfo) -> Bool {
sharedInstance.database!.open()
let isUpdated = sharedInstance.database!.executeUpdate("UPDATE student_info SET Name=?, Marks=? WHERE RollNo=?", withArgumentsInArray: [studentInfo.Name, studentInfo.Marks, studentInfo.RollNo])
sharedInstance.database!.close()
return isUpdated
}
func deleteStudentData(studentInfo: StudentInfo) -> Bool {
sharedInstance.database!.open()
let isDeleted = sharedInstance.database!.executeUpdate("DELETE FROM student_info WHERE RollNo=?", withArgumentsInArray: [studentInfo.RollNo])
sharedInstance.database!.close()
return isDeleted
}
func getAllStudentData() -> NSMutableArray {
sharedInstance.database!.open()
let resultSet: FMResultSet! = sharedInstance.database!.executeQuery("SELECT * FROM student_info", withArgumentsInArray: nil)
let marrStudentInfo : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
while resultSet.next() {
let studentInfo : StudentInfo = StudentInfo()
studentInfo.RollNo = resultSet.stringForColumn("RollNo")
studentInfo.Name = resultSet.stringForColumn("Name")
studentInfo.Marks = resultSet.stringForColumn("Marks")
marrStudentInfo.addObject(studentInfo)
}
}
sharedInstance.database!.close()
return marrStudentInfo
}
}
Now follow the same step create the new file choose swift file à give the name “EmployeeInfo” and click on create button after file created. Add the following code into the “EmployeeInfo.” 

import UIKit

let sharedInstance = ModelManager()
class ModelManager: NSObject {
var database: FMDatabase? = nil
class func getInstance() -> ModelManager
{
if(sharedInstance.database == nil)
{
sharedInstance.database = FMDatabase(path: Util.getPath("Employee.sqlite"))
}
return sharedInstance
}
func addStudentData(studentInfo: StudentInfo) -> Bool {
sharedInstance.database!.open()
let isInserted = sharedInstance.database!.executeUpdate("INSERT INTO employee_info (FirstName, LastName) VALUES (?, ?)", withArgumentsInArray: [studentInfo.Name, studentInfo.Marks])
sharedInstance.database!.close()
return isInserted
}
func updateStudentData(studentInfo: StudentInfo) -> Bool {
sharedInstance.database!.open()
let isUpdated = sharedInstance.database!.executeUpdate("UPDATE employee _info SET FirstName=?, LastName=? WHERE id=?", withArgumentsInArray: [studentInfo.Name, studentInfo.Marks, studentInfo.RollNo])
sharedInstance.database!.close()
return isUpdated
}
func deleteStudentData(studentInfo: StudentInfo) -> Bool {
sharedInstance.database!.open()
let isDeleted = sharedInstance.database!.executeUpdate("DELETE FROM employee_info WHERE id=?", withArgumentsInArray: [studentInfo.RollNo])
sharedInstance.database!.close()
return isDeleted
}
func getAllStudentData() -> NSMutableArray {
sharedInstance.database!.open()
let resultSet: FMResultSet! = sharedInstance.database!.executeQuery("SELECT * FROM employee_info", withArgumentsInArray: nil)
let marrStudentInfo : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
while resultSet.next() {
let studentInfo : StudentInfo = StudentInfo()
studentInfo.RollNo = resultSet.stringForColumn("id")
studentInfo.Name = resultSet.stringForColumn("FirstName")
studentInfo.Marks = resultSet.stringForColumn("LastName")
marrStudentInfo.addObject(studentInfo)
}
}
sharedInstance.database!.close()
return marrStudentInfo
}
}
 Now again follow the same step and create new file for that choose swift file à give name as “Util” and click on create button after file created add following code into “Util.swift” file.

import UIKit

class Util: NSObject {
class func getPath(fileName: String) -> String {
let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
let fileURL = documentsURL.URLByAppendingPathComponent(fileName)
return fileURL.path!
}
class func copyFile(fileName: NSString) {
let dbPath: String = getPath(fileName asString)
let fileManager = NSFileManager.defaultManager()
if !fileManager.fileExistsAtPath(dbPath) {
let documentsURL = NSBundle.mainBundle().resourceURL
let fromPath = documentsURL!.URLByAppendingPathComponent(fileName asString)
var error : NSError?
do {
try fileManager.copyItemAtPath(fromPath.path!, toPath: dbPath)
catch let error1 asNSError {
error = error1
}
let alert: UIAlertView = UIAlertView()
if (error != nil) {
alert.title = "Error Occured"
alert.message = error?.localizedDescription
else {
alert.title = "Successfully Copy"
alert.message = "Your database copy successfully"
}
alert.delegate = nil
alert.addButtonWithTitle("Ok")
alert.show()
}
}
class func invokeAlertMethod(strTitle: NSString, strBody: NSString, delegate: AnyObject?) {
let alert: UIAlertView = UIAlertView()
alert.message = strBody asString
alert.title = strTitle asString
alert.delegate = delegate
alert.addButtonWithTitle("Ok")
alert.show()
}
}
Now we will run and check the output of application. To run application, select the required simulator (Here we selected iPhone 6s Plus) and click on Play button, located at the top-left corner of the Xcode toolbar like as shown below. 

Run ios sqlite database app using play button in simulator

Output of iOS SQLite App in Swift

Following is the result of iOS SQLite app. Now click on insert button it will take you to user form in that enter user details and click on save button like as shown below.

iOS SQLite Database App Example Result or Output

Once we enter details and click on save button that will take you to first screen where you can see the entered user details with Edit and Delete options. Now click on Delete button to delete record from tableview.

iOS SQLite Database App Example Result or Output

This is how we can use SQLite database in our iOS swift applications based on our requirements. 

How to DROP SEQUENCE in Oracle?

  Oracle  DROP SEQUENCE   overview The  DROP SEQUENCE  the statement allows you to remove a sequence from the database. Here is the basic sy...