以编程方式将Sqlite数据库导入设备

时间:2014-04-15 12:00:01

标签: android sqlite

我已经设法将SQLite数据库导出到SD卡现在如果有人帮助将Sqlite数据库导入设备,我将不胜感激?

我是android中的newbi我已经尝试了很多但没有成功。

编辑...

public class MainActivity extends Activity implements OnClickListener {

private static final String SAMPLE_DB_NAME = "TrekBook";
private static final String SAMPLE_TABLE_NAME = "Info";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    findViewById(R.id.button1).setOnClickListener(this);
    findViewById(R.id.button2).setOnClickListener(this);
    findViewById(R.id.button3).setOnClickListener(this);
    findViewById(R.id.button4).setOnClickListener(this);

}
@Override
public void onClick(View v) {
    switch(v.getId()) {
    case R.id.button1:
        deleteDB();
        break;
    case R.id.button2:
        exportDB();
        break;
    case R.id.button3:
        createDB();
        break;
    case R.id.button4:
        importDB();
        break;  
    }
}

private void deleteDB(){
    boolean result = this.deleteDatabase(SAMPLE_DB_NAME);
    if (result==true) {
         Toast.makeText(this, "DB Deleted!", Toast.LENGTH_LONG).show();
    } 
}

private void exportDB(){
    File sd = Environment.getExternalStorageDirectory();
    File data = Environment.getDataDirectory();
    FileChannel source=null;
    FileChannel destination=null;
    String currentDBPath = "/data/"+ "com.authorwjf.sqliteexport" +"/databases/"+SAMPLE_DB_NAME;
    String backupDBPath = SAMPLE_DB_NAME;
    File currentDB = new File(data, currentDBPath);
    File backupDB = new File(sd, backupDBPath);
    try {
        source = new FileInputStream(currentDB).getChannel();
        destination = new FileOutputStream(backupDB).getChannel();
        destination.transferFrom(source, 0, source.size());
        source.close();
        destination.close();
        Toast.makeText(this, "DB Exported!", Toast.LENGTH_LONG).show();
    } catch(IOException e) {
        e.printStackTrace();
    }
}

private void createDB() {
    SQLiteDatabase sampleDB =  this.openOrCreateDatabase(SAMPLE_DB_NAME, MODE_PRIVATE, null);
    sampleDB.execSQL("CREATE TABLE IF NOT EXISTS " +
            SAMPLE_TABLE_NAME +
            " (LastName VARCHAR, FirstName VARCHAR," +
            " Rank VARCHAR);");
    sampleDB.execSQL("INSERT INTO " +
            SAMPLE_TABLE_NAME +
            " Values ('Kirk','James, T','Captain');");
    sampleDB.close();
    sampleDB.getPath();
    Toast.makeText(this, "DB Created @ "+sampleDB.getPath(), Toast.LENGTH_LONG).show(); 
}

private void importDB(){
    File f=new File("/data/data/com.authorwjf.sqliteexport/databases/TrekBook");
    FileInputStream fis=null;
    FileOutputStream fos=null;

    try
    {
      fis=new FileInputStream(f);
      fos=new FileOutputStream("/mnt/sdcard/DB/TrekBook");
      while(true)
      {
        int i=fis.read();
        if(i!=-1)
        {fos.write(i);}
        else
        {break;}
      }
      fos.flush();
      Toast.makeText(this, "DB dump OK", Toast.LENGTH_LONG).show();
    }
    catch(Exception e)
    {
      e.printStackTrace();
      Toast.makeText(this, "DB dump ERROR", Toast.LENGTH_LONG).show();
    }
    finally
    {
      try
      {
        fos.close();
        fis.close();
      }
      catch(Exception ioe)
      {}
    }
}

 }

activity_main

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="SQLite DB to SD Demo"/>

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Delete" />
<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Export" />
<Button
    android:id="@+id/button3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Create" />
<Button
    android:id="@+id/button4"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Import" />

</LinearLayout>

提前致谢......

3 个答案:

答案 0 :(得分:0)

尝试这种方式:

File f=new File("/data/data/com.example.sql/databases/DBNAME");
                    FileInputStream fis=null;
                    FileOutputStream fos=null;

                    try
                    {
                      fis=new FileInputStream(f);
                      fos=new FileOutputStream("/mnt/sdcard/DB/database");
                      while(true)
                      {
                        int i=fis.read();
                        if(i!=-1)
                        {fos.write(i);}
                        else
                        {break;}
                      }
                      fos.flush();
                      Toast.makeText(this, "DB dump OK", Toast.LENGTH_LONG).show();
                    }
                    catch(Exception e)
                    {
                      e.printStackTrace();
                      Toast.makeText(this, "DB dump ERROR", Toast.LENGTH_LONG).show();
                    }
                    finally
                    {
                      try
                      {
                        fos.close();
                        fis.close();
                      }
                      catch(Exception ioe)
                      {}
                    }

不要忘记在manifest.xml中添加权限

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

答案 1 :(得分:0)

将Sqlite数据库导入设备 -

try {
            backupDatabase();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }


public static void backupDatabase() throws IOException {
        //Open your local db as the input stream
        String inFileName = "/data/data/com.myapp.main/databases/Content";
        File dbFile = new File(inFileName);
        FileInputStream fis = new FileInputStream(dbFile);

        String outFileName = Environment.getExternalStorageDirectory()+"/Content";
        //Open the empty db as the output stream
        OutputStream output = new FileOutputStream(outFileName);
        //transfer bytes from the inputfile to the outputfile
        byte[] buffer = new byte[1024];
        int length;
        while ((length = fis.read(buffer))>0){
            output.write(buffer, 0, length);
        }
        //Close the streams
        output.flush();
        output.close();
        fis.close();
    }

要检查此数据库,您必须在控制台(例如

)中从应用程序路径发出命令
adb pull mnt/sdcard/Content

其中,

内容是您在上面提供的inFileName内容。

当然,您必须更改应用程序适用的inFileNameoutFileName以及导出它的位置以及要在设备中导入的位置。

答案 2 :(得分:0)

如果您的设备已植根,请尝试这种邪恶方式。否则你无法将DB从手机拉到sdCard:

    public void copyDbToSdcard()
{
    try
    {
        String comando = "cp -r /data/data/com.package.name/Databases/DB_File.db /sdcard/Your_Custom_Folder/";
        Process suProcess = Runtime.getRuntime().exec("su");
        DataOutputStream os = new DataOutputStream(suProcess.getOutputStream());
        os.writeBytes(comando + "\n");
        os.flush();
        os.writeBytes("exit\n");
        os.flush();
        try
        {
            int suProcessRetval = suProcess.waitFor();
            if(255 != suProcessRetval)
            {
                Log.e("SU", "If Part");
            }
            else
            {
                Log.e("SU", "Else Part");
            }
        }
        catch (Exception ex)
        {
            Log.e("ERROR-->", ex.toString());
        }
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}  

享受:)

相关问题