Question

First time,I ran the app and insert data by createDefaultUser() into storage.db (Database Version 1).
Second time,I ran the app (Database Version 2), DatabaseManager.java functions onUpgrade() well. Logcats showed OK.
But onUpgrade() there is a problem,that is, SQLiteDatabase.exe(sql) insert nothing where sql is not "null" and is a string read from file.

Here is MainActivity.java:

package com.example.textbase;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new AsyncDatabase().execute();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    private class AsyncDatabase extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {
            DatabaseManager db = new DatabaseManager(getApplicationContext());
            db.createDatabase();
            db.getWritableDatabase();
            //db.createDefaultUser();
            return null;
        } 

        @Override
        protected void onPostExecute(Void result) {
            TextView txt=(TextView)findViewById(R.id.textView);
            txt.setText("Done");
        }

        @Override
        protected void onPreExecute() {
            TextView txt=(TextView)findViewById(R.id.textView);
            txt.setText("Loading");
        }

        @Override
        protected void onProgressUpdate(Void... values) {

        }
    }
}


Here is DatabaseManager.java:

package com.example.textbase;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DatabaseManager extends SQLiteOpenHelper{

    private static final String DATABASE_PATH = "/data/data/com.example.textbase/databases/";
    private static final String DATABASE_NAME = "storage.db";
    private static final String CACHE_NAME="temp_favourite";
    private static final int DATABASE_VERSION =2;
    private final Context context; 

    public DatabaseManager(Context context){
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.context=context;
    }
    @Override
    public void onCreate(SQLiteDatabase database) {

    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        if(oldVersion<newVersion){
            Log.i("Database","New database is being upgraded.");

            exportFavourite(db);
            Log.i("Favourite","Favourite file has been exported.");

            File f=new File(DATABASE_PATH+DATABASE_NAME);
            f.delete();
            Log.i("Database","Old database has been deleted.");

            copyDatabase();
            Log.i("Database","New database has been created.");

            importFavourite(db);
            Log.i("Favourite","Favourite file has been imported into database.");

            f=new File(context.getFilesDir()+"/"+CACHE_NAME);
            f.delete();
            Log.i("Favourite","Favourite file has been deleted.");
        }
    }

    public void createDatabase(){
        boolean dbExist=checkDatabase();
        if(dbExist){
            Log.i("Database","Database exists.");
        }else{
            copyDatabase();
        }
    }

    private void copyDatabase(){
        File databaseFile = new File(DATABASE_PATH);
        // check if databases folder exists, if not create one and its subfolders
        if (!databaseFile.exists()){
            databaseFile.mkdir();
            Log.i("Directory","Database directory has been created.");
        }
        String outFilename =null;
        outFilename = DATABASE_PATH +DATABASE_NAME;
        File sampleFile = new File(outFilename);
        try {
            InputStream in = context.getAssets().open(DATABASE_NAME);
            OutputStream out = new FileOutputStream(outFilename);
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            out.flush();
            out.close();
            in.close();
            Log.i("Database","Database has been copied from asset folder.");
            }catch(IOException e) {
            }
    }

    private boolean checkDatabase() {
        SQLiteDatabase checkDB = null;
        try {
            String fullPath = DATABASE_PATH + DATABASE_NAME;
            checkDB = SQLiteDatabase.openDatabase(fullPath, null,SQLiteDatabase.OPEN_READONLY);
        } catch (SQLiteException e) {
            e.printStackTrace();
        }

        if (checkDB != null) {
            checkDB.close();

        }
        return checkDB != null ? true : false;
    }

    private void setQuerytoFile(String str){
        FileOutputStream outputStream;
        try {
          outputStream = context.openFileOutput(CACHE_NAME, Context.MODE_APPEND);
          outputStream.write(str.getBytes());
          outputStream.close();
        } catch (Exception e) {
          e.printStackTrace();
        }
    }

    public void exportFavourite(SQLiteDatabase db){
        String sql = "SELECT * FROM user";
        Cursor cursor = db.rawQuery(sql, null);
        if (cursor.moveToFirst()) {
            do {
                String username=cursor.getString(1);
                int password=Integer.parseInt(cursor.getString(2));
                String query="insert into user(username,password) values('"+username+"',"+password+");";
                setQuerytoFile(query);
            } while (cursor.moveToNext());
        }
    }

    private String getQueryfromFile() throws IOException{
        BufferedReader in = null;
        File file=new File(context.getFilesDir()+"/"+CACHE_NAME);
        FileInputStream fin=new FileInputStream(file);
        InputStream is=fin;
        try
        {
            in = new BufferedReader(new InputStreamReader(is));
            String line;
            final StringBuilder buffer = new StringBuilder();
            while ((line = in.readLine()) != null)
            {
                buffer.append(line);
            }
            return buffer.toString();
        }
        catch (final IOException e)
        {
            return "";
        }
        finally
        {
            try
            {
                in.close();
            }
            catch (IOException e)
            {
                // ignore //
            }
        }
    }

    private void importFavourite(SQLiteDatabase db){
        File f=new File(context.getFilesDir()+"/"+CACHE_NAME);
        if(f.exists()){
            String sql;
            try {
                sql = getQueryfromFile();
                Log.i("SQL Query",sql);
                db.execSQL(sql);
                Log.i("Database","Favourite backup has been imported.");             
                f.delete();
                Log.i("File","Favourite backup file has been deleted.");
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }else{
            Log.i("File","Favourite backup file does not exist.");
        }
    }

    public void createDefaultUser(){
        String sql="insert into user(username,password) values('Administrator','123');";
        getWritableDatabase().execSQL(sql);
        Log.i("User","Created default user");
    }
}


Here is Logcat while upgrading database:

12-11 21:19:37.320: I/Database(4358): Database exists.
12-11 21:19:37.590: I/Database(4358): New database is being upgraded.
12-11 21:19:37.620: I/Favourite(4358): Favourite file has been exported.
12-11 21:19:37.620: I/Database(4358): Old database has been deleted.
12-11 21:19:37.630: I/Database(4358): Database has been copied from asset folder.
12-11 21:19:37.630: I/Database(4358): New database has been created.
12-11 21:19:37.650: I/SQL Query(4358): insert into user(username,password) values('Administrator',123);insert into user(username,password) values('Administrator',123);insert into user(username,password) values('Administrator',123);
12-11 21:19:37.660: I/Database(4358): Favourite backup has been imported.
12-11 21:19:37.660: I/File(4358): Favourite backup file has been deleted.
12-11 21:19:37.660: I/Favourite(4358): Favourite file has been imported into database.
12-11 21:19:37.660: I/Favourite(4358): Favourite file has been deleted.


Here is Database(storage.db) Table Scheme:

CREATE TABLE "android_metadata" ("locale" TEXT DEFAULT 'en_US');
CREATE TABLE [user] (
[user_id] INTEGER  NOT NULL PRIMARY KEY AUTOINCREMENT,
[username] VARCHAR(255)  NULL,
[password] VARCHAR(255)  NULL
);


I want to exec(sql) successfully. How can I?
Why SQLiteDatabase.exec() insert nothing?

Was it helpful?

Solution

As you can read in the official docs:

public void execSQL (String sql) Execute a single SQL statement that is NOT a SELECT or any other SQL statement that returns data.

Parameters

sql the SQL statement to be executed. Multiple statements separated by semicolons are not supported.

Is important to read and understand the references before using any function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top