Simple use of conditional database Android:sqllite _android

Source: Internet
Author: User
Tags sqlite sqlite database static class

SQLite analysis

SQLite is a lightweight, embedded, relational database that has now been used in iphone, Android, and other mobile systems, SQLite portability, easy to use, small, efficient and reliable. SQLite embedded in the application application, they share the same process space, rather than a separate process. Externally, it's not like an RDBMS, but within the process, it's a complete, self-contained database engine.

In Android, you need to lose a Sqliteopenhelper object when you need to manipulate the SQLite database, and Sqliteopenhelper is an abstract class that users need to inherit and implement some of the methods in the class.

1. After inheriting sqliteopenhelper, we have the following two methods:

Getreadabledatabase () Create or open a query database

Getwritabledatabase () Create or open a writable database

They return to the city Sqlitedatabase objects, the user through the lost Sqlitedatabase object for subsequent operations

2, at the same time the user can also overwrite the following callback function, and then the operation of the database callback the following methods:

OnCreate (Sqlitedatabase): This method is called when the database is first created, and we typically create a database table in this method.

Onupgrade (Sqlitedatabase,int,int): When the database needs to be modified, the Android system takes the initiative to call this method. In general, we delete the database table in this method, and create a new database table, of course, we need to do other operations, complete depending on the requirements of the application.

OnOpen (sqlitedatabase): This is a callback function when the database is opened, and is not generally used.

Need to be aware

1, in the Sqliteoepnhelper subclass, you must have the following constructor

Copy Code code as follows:

Public Databasehelper (context, String name, Cursorfactory factory,
int version) {
Constructors in parent classes must be called through Super
Super (context, name, Factory, version);
For convenience, you can also create other constructors, including two parameters or three parameters.

2. The function public void onCreate (Sqlitedatabase db) is executed when the getreadabledatabase () is invoked () or getwritabledatabase () first created the database. This method is actually invoked when the Sqlitedatabse object is lost for the first time.

public void OnCreate (Sqlitedatabase db) {
System.out.println ("Create a Database");
The Execsql function is used to execute SQL statements
Db.execsql ("CREATE table user (ID int,name varchar (20))");
}

The above is a good example, you can refer to the following

Copy Code code as follows:

public class DBHelper {

private static Databasehelper Mdbhelper;
private static Sqlitedatabase mDb;

private static final String database_name = "Life";

private static final int database_version = 1;

Private context Mctx;

private static class Databasehelper extends Sqliteopenhelper {

Databasehelper (Context context) {
Super (context, database_name, NULL, database_version);
}

@Override
public void OnCreate (Sqlitedatabase db) {
Establishment table Structure
Db.execsql ("CREATE TABLE life_history" (id INTEGER PRIMARY KEY autoincrement,type text, city text, company text, Pucnum TEX T, Pucname TEXT);
}

@Override
public void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {
}
}

Public DBHelper (Context ctx) throws SQLException {
This.mctx = CTX;
Mdbhelper = new Databasehelper (MCTX);
MDb = Mdbhelper.getwritabledatabase ();
}

/**
* Close the data source
*/
public void CloseConnection () {
if (mDb!= null && mdb.isopen ())
Mdb.close ();
if (mdbhelper!= null)
Mdbhelper.close ();
}

/**
* Insert Data parameter
* @param tablename Table name
* @param initialvalues the column corresponding to the value to insert
* @return
*/
Public long Insert (String tablename, contentvalues initialvalues) {

Return Mdb.insert (tablename, NULL, initialvalues);
}

/**
* Delete Data
* @param tablename Table name
* @param deletecondition conditions
* @param the value of the Deleteargs condition (if Deletecondition has "? "Number, which will be replaced with the value in this array, corresponding to the
* @return
*/
public boolean Delete (String tablename, String deletecondition, string[] deleteargs) {

Return Mdb.delete (tablename, deletecondition, Deleteargs) > 0;
}

/**
* Update Data
* @param tablename Table name
* @param initialvalues The column to be updated
* @param selection Update conditions
* @param selectargs update condition "? "Corresponds to the value
* @return
*/
public boolean update (string tablename, Contentvalues initialvalues, string selection, string[] selectargs) {
Return Mdb.update (tablename, initialvalues, Selection, Selectargs) > 0;
}

/**
* Get a list
* @param distinct whether to repeat
* @param tablename Table name
* @param columns the column to return
* @param selection conditions
* @param selectionargs conditions "? The parameter value
* @param groupBy Group
* @param having packet filter conditions
* @param ordered by
* @return
*/
Public Cursor findlist (boolean distinct, String tablename, string[] columns, string selection, string[] Selectionargs, STR ing groupBy, string having, string by, string limit {

Return Mdb.query (DISTINCT, tablename, columns, selection, Selectionargs, GroupBy, have, by, limit);
}

   /**
     * Get single-line record
     * @param tablename table name
& nbsp;    * @param columns gets the array of columns
     * @param selection conditions
      * @param selectionargs conditions "? "Corresponding value
     * @param groupBy Group
     * @param having group conditions
      * @param by order
     * @param limit data range
     * @param dis Tinct whether to repeat
     * @return
     * @throws SQLException
      */
    public Cursor findone (boolean distinct, String tablename, string[] columns, string Selection, string[] Selectionargs, String groupBy, String having, string by, string limit) throws SQLException {

Cursor mcursor = findlist (DISTINCT, tablename, columns, selection, Selectionargs, GroupBy, having, by, by, limit);

if (mcursor!= null) {
Mcursor.movetofirst ();
}
return mcursor;

}

/**
* Execute SQL (with parameters)
* @param sql
* @param args sql "? The parameter value
*/
public void Execsql (String sql, object[] args) {
Mdb.execsql (sql, args);

}

/**
* Execute SQL
* @param sql
*/
public void Execsql (String sql) {
Mdb.execsql (SQL);

}

/**
* To determine whether a table exists
* @param tabname table name
* @return
*/
public boolean istableexist (String tablename) {
Boolean result = false;
if (tablename = = null) {
return false;
}

try {
Cursor Cursor = null;
String sql = "SELECT COUNT (1) as C from sqlite_master where type = ' table ' and name = '" + Tablename.trim () + "'";
cursor = mdb.rawquery (sql, NULL);
if (Cursor.movetonext ()) {
int count = cursor.getint (0);
if (Count > 0) {
result = true;
}
}

Cursor.close ();
}
catch (Exception e) {
}
return result;
}

/**
* Determine if a field exists in a table (note, this method cannot determine whether the table exists, and should therefore be applied with istableexist)
* @param tabname table name
* @param columnName Column Name
* @return
*/
public boolean iscolumnexist (string tablename, string columnName) {
Boolean result = false;
if (tablename = = null) {
return false;
}

try {
Cursor Cursor = null;
String sql = SELECT COUNT (1) as C from sqlite_master where type = ' table ' and name = ' + Tablename.trim () + ' ' and SQL lik E '% ' + columnname.trim () + "%";
cursor = mdb.rawquery (sql, NULL);
if (Cursor.movetonext ()) {
int count = cursor.getint (0);
if (Count > 0) {
result = true;
}
}

Cursor.close ();
}
catch (Exception e) {
}
return result;
}

}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.