sqlite使用 包括外键
IntroductionAndroid default Database engine is Lite. SQLite is a lightweight transactional database engine that occupies a small amount of disk storage and memory,so it's a perfect choice for creating databases on many mobile operating systems such as Android,iOS. Things to consider when dealing with SQLite:
In this tutorial,we will create a simple database application to store employees data. the DB has: Tables
Views
Creating SQLite DatabaseBy default,SQLite on Android does not have a management interface or an application to create and manage databases from,so we're going to create the database ourselves by code. First,we will create a class that handles all the operations required to deal with the database such as creating the database,creating tables,inserting and deleting records and so on. The first step is to create a class that inherits from
Our class will have the following members: Collapse | Copy Codepublic class DatabaseHelper extends SQLiteOpenHelper {
static final String dbName="demoDB";
static final String employeeTable="Employees";
static final String colID="EmployeeID";
static final String colName="EmployeeName";
static final String colAge="Age";
static final String colDept="Dept";
static final String deptTable="Dept";
static final String colDeptID="DeptID";
static final String colDeptName="DeptName";
static final String viewEmps="ViewEmps";
The ConstructorCollapse | Copy Codepublic DatabaseHelper(Context context) {
super(context,dbName,null,33);
}
The constructor of the super class has the following parameters:
Creating the DatabaseThe first superclass method to override is public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE "+deptTable+" ("+colDeptID+ " INTEGER PRIMARY KEY,"+
colDeptName+ " TEXT)");
db.execSQL("CREATE TABLE "+employeeTable+"
("+colID+" INTEGER PRIMARY KEY AUTOINCREMENT,"+
colName+" TEXT,"+colAge+" Integer,"+colDept+"
INTEGER NOT NULL,FOREIGN KEY ("+colDept+") REFERENCES
"+deptTable+" ("+colDeptID+"));");
db.execSQL("CREATE TRIGGER fk_empdept_deptid " +
" BEFORE INSERT "+
" ON "+employeeTable+
" FOR EACH ROW BEGIN"+
" SELECT CASE WHEN ((SELECT "+colDeptID+" FROM "+deptTable+"
WHERE "+colDeptID+"=new."+colDept+" ) IS NULL)"+
" THEN RAISE (ABORT,'Foreign Key Violation') END;"+
" END;");
db.execSQL("CREATE VIEW "+viewEmps+
" AS SELECT "+employeeTable+"."+colID+" AS _id,"+
" "+employeeTable+"."+colName+","+
" "+employeeTable+"."+colAge+","+
" "+deptTable+"."+colDeptName+""+
" FROM "+employeeTable+" JOIN "+deptTable+
" ON "+employeeTable+"."+colDept+" ="+deptTable+"."+colDeptID
);
//Inserts pre-defined departments
InsertDepts(db);
}
The method creates tables with columns,a view and a trigger. The method is invoked when the database is created. So we create our table and specify the columns. This method is invoked when the database does not exist on the disk,it’s executed only once on the same device the first time the application is run on the device. Upgrading the DatabaseSometimes,we want to upgrade the database by changing the schema,add new tables or change column data types. This is done by overriding the public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS "+employeeTable);
db.execSQL("DROP TABLE IF EXISTS "+deptTable);
db.execSQL("DROP TRIGGER IF EXISTS dept_id_trigger");
db.execSQL("DROP TRIGGER IF EXISTS dept_id_trigger22");
db.execSQL("DROP TRIGGER IF EXISTS fk_empdept_deptid");
db.execSQL("DROP VIEW IF EXISTS "+viewEmps);
onCreate(db);
}
This method is invoked when the version number specified in the constructor of the class changes. When you want to append a change to your database,you must change the version number in the constructor of the class. So when you pass the constructor a version number of 2: Collapse | Copy Codepublic DatabaseHelper(Context context) {
super(context,2);
// TODO Auto-generated constructor stub
}
instead of 1: Collapse | Copy Codesuper(context,2);
the application understands that you want to upgrade the database and Managing Foreign-Key ConstraintsWe mentioned before that SQLite 3 by default does not support foreign key constraint,however we can force such a constraint usingTRIGGERS: we will create a trigger that ensures that when a new CREATE TRIGGER fk_empdept_deptid Before INSERT ON Employees
FOR EACH ROW BEGIN
SELECT CASE WHEN ((SELECT DeptID FROM Dept WHERE DeptID =new.Dept ) IS NULL)
THEN RAISE (ABORT,'Foreign Key Violation') END;
END
In db.execSQL("CREATE TRIGGER fk_empdept_deptid " +
" BEFORE INSERT "+
" ON "+employeeTable+
" FOR EACH ROW BEGIN"+
" SELECT CASE WHEN ((SELECT "+colDeptID+" FROM "+deptTable+" _
WHERE "+colDeptID+"=new."+colDept+" ) IS NULL)"+
" THEN RAISE (ABORT,'Foreign Key Violation') END;"+
" END;");
Executing SQL StatementsNow let's begin executing basic SQL statements. You can execute any SQL statementthat is not a query whether it is db.execSQL("CREATE TABLE "+deptTable+" ("+colDeptID+ " INTEGER PRIMARY KEY,"+
colDeptName+ " TEXT)");
Inserting RecordsWe insert records to the database using the following code for example to insert records in the SQLiteDatabase db=this.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(colDeptID,1);
cv.put(colDeptName,"Sales");
db.insert(deptTable,colDeptID,cv);
cv.put(colDeptID,2);
cv.put(colDeptName,"IT");
db.insert(deptTable,cv);
db.close();
Notice that we need to call Updating ValuesTo execute an
public int UpdateEmp(Employee emp)
{
SQLiteDatabase db=this.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(colName,emp.getName());
cv.put(colAge,emp.getAge());
cv.put(colDept,emp.getDept());
return db.update(employeeTable,cv,colID+"=?",new String []{String.valueOf(emp.getID())});
}
The
Deleting RowsAs in
public void DeleteEmp(Employee emp)
{
SQLiteDatabase db=this.getWritableDatabase();
db.delete(employeeTable,new String [] {String.valueOf(emp.getID())});
db.close();
}
The Executing QueriesTo execute queries,there are two methods:
To execute a raw query to retrieve all departments: Collapse | Copy CodeCursor getAllDepts()
{
SQLiteDatabase db=this.getReadableDatabase();
Cursor cur=db.rawQuery("SELECT "+colDeptID+" as _id,"+colDeptName+" from "+deptTable,new String [] {});
return cur;
}
The
Notes
Another way to perform a query is to use a public Cursor getEmpByDept(String Dept)
{
SQLiteDatabase db=this.getReadableDatabase();
String [] columns=new String[]{"_id",colName,colAge,colDeptName};
Cursor c=db.query(viewEmps,columns,colDeptName+"=?",new String[]{Dept},null);
return c;
}
The
Managing CursorsResult sets of queries are returned in
There are also some useful methods to check the position of a cursor: public int GetDeptID(String Dept)
{
SQLiteDatabase db=this.getReadableDatabase();
Cursor c=db.query(deptTable,new String[]{colDeptID+" as _id",colDeptName},null);
//Cursor c=db.rawQuery("SELECT "+colDeptID+" as _id FROM "+deptTable+"
//WHERE "+colDeptName+"=?",new String []{Dept});
c.moveToFirst();
return c.getInt(c.getColumnIndex("_id"));
}
We have Also there are Download a sample application on using database in Android from here. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |