为什么SQLiteDatabase.exec()什么都不插入?

时间:2013-12-11 15:17:09

标签: java android android-sqlite sqliteopenhelper

我第一次运行应用程序并将createDefaultUser()的数据插入storage.db(数据库版本1)。
第二次,我运行了应用程序(数据库版本2),DatabaseManager.java函数onUpgrade()。 Logcats表现良好。
但是onUpgrade()存在一个问题,即SQLiteDatabase.exe(sql)在sql不是“null”的地方插入任何内容,并且是从文件读取的字符串。

这是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) {

        }
    }
}


这是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");
    }
}


这是升级数据库时的Logcat:

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.


这是数据库(storage.db)表格方案:

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
);


我想成功执行exec(sql)。我怎么能? 为什么SQLiteDatabase.exec()什么都不插入?

1 个答案:

答案 0 :(得分:0)

您可以阅读the official docs

  

public void execSQL(String sql)   执行一个非SELECT的SQL语句或任何其他返回数据的SQL语句。

     

<强>参数

     

sql要执行的SQL语句。 多个陈述   不支持以分号分隔。

在使用任何函数之前阅读和理解参考文献很重要。