Android creates databases based on SQL files and inserts data

Source: Internet
Author: User

Android creates databases based on SQL files and inserts data

During client development, data written on the server is duplicated and you do not need to access the server. Then, the server provides an SQL file containing the database and data, it is impossible for these development clients to manually store data in one row and one row, right? So I thought of reading the SQL file directly to create data and insert data.

Create DBHelp and inherit SQLiteOpenHelper

Public class DBHelper extends SQLiteOpenHelper {private Context mContext; public DBHelper (Context context, String databaseName, CursorFactory factory, int version) {super (context, databaseName, factory, version ); mContext = context;}/*** call **/@ Overridepublic void onCreate (SQLiteDatabase db) {if (! TabIsExist ("test", db) {executeAssetsSQL (db, "test. SQL "); // db.exe cSQL (SQL); // System. out. println ("create table");}/*** called during Database Upgrade **/@ Overridepublic void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion) {// The database does not upgrade if (newVersion <= oldVersion) {return;} Configuration. oldVersion = oldVersion; int changeCnt = newVersion-oldVersion; for (int I = 0; I <changeCnt; I ++) {// execute the updatei_ I + 1 file in sequence and update from 1 to 2 [1-2], 2 updated to 3 [2-3] String schemaName = "update" + (oldVersion + I) + "_" + (oldVersion + I + 1) + ". SQL "; executeAssetsSQL (db, schemaName) ;}}/*** read database files (. SQL), and execute the SQL statement **/private void executeAssetsSQL (SQLiteDatabase db, String schemaName) {BufferedReader in = null; try {in = new BufferedReader (new InputStreamReader (mContext. getAssets (). open (Configuration. DB_PATH + "/" + schemaName); // System. out. pri Ntln ("Path:" + Configuration. DB_PATH + "/" + schemaName); String line; String buffer = ""; while (line = in. readLine ())! = Null) {buffer + = line; if (line. trim (). endsWith (";") mongodb.exe cSQL (buffer. replace (";", ""); buffer = "" ;}} catch (IOException e) {Log. e ("db-error", e. toString ();} finally {try {if (in! = Null) in. close ();} catch (IOException e) {Log. e ("db-error", e. toString () ;}} public List selectAllCities (SQLiteDatabase db) {List areas = new ArrayList (); Area area; String SQL = "select * from test where area_level =? "; Cursor cursor = db. rawQuery (SQL, new String [] {"" + 0}); while (cursor. moveToNext () {area = new Area (); area. setId (cursor. getInt (0); area. setArea_name (cursor. getString (2); areas. add (area); area = null;} cursor. close (); return areas;} public List selectAllAreas (SQLiteDatabase db, int parent_id) {List areas = new ArrayList (); Area area; string SQL = "select * from test where parent_id =? "; Cursor cursor = db. rawQuery (SQL, new String [] {"" + parent_id}); while (cursor. moveToNext () {area = new Area (); area. setId (cursor. getInt (0); area. setArea_name (cursor. getString (2); areas. add (area); area = null;} cursor. close (); return areas;}/*** determines whether a table exists * @ param tabName * @ param db * @ return */public boolean tabIsExist (String tabName, SQLiteDatabase db) {boolean result = false; if (tabName = null) {return false;} Cursor cursor = null; try {String SQL = "select count (*) as c from sqlite_master where type = 'table' and name = '"+ tabName. trim () + "'"; cursor = db. rawQuery (SQL, null); if (cursor. moveToNext () {int count = cursor. getInt (0); if (count> 0) {result = true ;}} catch (Exception e) {} return result ;}}

Configuration. java is a constant.

public class Configuration {public static final String DB_PATH = "schema";public static final String DB_NAME = "test.db";public static final int DB_VERSION = 1;public static int oldVersion = -1;}
The SQL file is stored in assets-> schema-> test. SQL

In fact, this process is very simple and easy to understand, that is, to read the file according to the path, then read the content in the file, and then according to the keyword, sqllite will automatically perform corresponding operations, therefore, the SQL statements in this SQL file must be standardized, otherwise they will not be written.

Call in activity:

dbHelper = new DBHelper(this, "test", null, 1);dbHelper.onCreate(dbHelper.getWritableDatabase());




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.