SQLiteCopy

来源:互联网 发布:全球生产网络弊端 编辑:程序博客网 时间:2024/06/07 00:00

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import com.bwie.day2sqlite.R;
import com.hgz.day6sqlite.dao.Dao;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

    private Dao dao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btnAdd = (Button) findViewById(R.id.btnAdd);
        Button btnUpdate = (Button) findViewById(R.id.btnUpdate);
        Button btnDelete = (Button) findViewById(R.id.btnDelete);
        Button btnFindAll = (Button) findViewById(R.id.btnFindAll);
        Button btnFindCondition = (Button) findViewById(R.id.btnFindCondition);
        Button btnCopy = (Button) findViewById(R.id.btnCopy);
        
        
        btnAdd.setOnClickListener(this);
        btnUpdate.setOnClickListener(this);
        btnDelete.setOnClickListener(this);
        btnFindAll.setOnClickListener(this);
        btnFindCondition.setOnClickListener(this);

        btnCopy.setOnClickListener(this);

        //实例化Dao类

        dao = new Dao(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.btnAdd:
            dao.add("heguozhong", "130");
            break;
        case R.id.btnUpdate:
            dao.update("heguo", "1111", 5);
            break;
        case R.id.btnDelete:
            dao.delete(1);
            break;
        case R.id.btnFindAll:
            String string = dao.findAll();
            Toast.makeText(MainActivity.this, string, Toast.LENGTH_SHORT).show();
            break;
        case R.id.btnFindCondition:
            String str = dao.findConditon(5);
            Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();
            break;
        case R.id.btnCopy:
            copyDatabase();
            break;
        default:
            break;
        }
    }
    //备份数据库
    @SuppressWarnings("resource")
    private void copyDatabase() {
        //关联到需要备份的数据库
        File file = new File("/data/data/"+getPackageName()+"/databases","user.db");
        System.out.println("文件目录 : "+file.getPath());
        try {
            FileInputStream is = new FileInputStream(file);
            
            //备份数据库到那个目的地(位置),sdcard
            //getExternalStorageDirectory() 拿到的是一个sdcrad根目录
            File file2 = new File(Environment.getExternalStorageDirectory(), "copyUser.db");
            System.out.println("路径 : "+Environment.getExternalStorageDirectory().getPath());
            FileOutputStream os = new FileOutputStream(file2);
            byte[] buffer=new byte[1024];
            int length=0;
            while ((length=is.read(buffer))!=-1) {
                os.write(buffer, 0, length);
            }
            is.close();
            os.close();
            Toast.makeText(this, "备份数据库成功", 0).show();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "备份数据库失败", 0).show();
        }
    }

}


//SQLite类

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class SQLite extends SQLiteOpenHelper {

    public SQLite(Context context) {
        // context 上下文
        // name 数据库的名字
        // factory 游标工厂 填null 代表的是使用系统自带的游标工厂
        // version 数据库的版本 必须 >= 1
        super(context, "user.db", null, 1);
    }
    /**
     * 这个方法是数据库第一次被创建的时候会被调用,只会执行一次
     * 通常用于初始化表结构
     *
     */
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table user(_id Integer primary key autoincrement,name varchar(20),phone varchar(20))");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

}

//Dao类

import com.hgz.day6sqlite.SQLite;
import android.R.integer;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class Dao {
    private SQLiteDatabase db;

    public Dao(Context context) {
        SQLite sqLite = new SQLite(context);
        // 得到操作数据库的实例对象
        db = sqLite.getWritableDatabase();
    }

    public void add(String name, String phone) {
        db.execSQL("insert into user(name,phone) values(?,?)", new Object[] {
                name, phone });
    }

    public void update(String name, String phone, int id) {
        db.execSQL("update user set name=?,phone=? where _id=?", new Object[] {
                name, phone, String.valueOf(id) });
    }

    public void delete(int id) {
        db.execSQL("delete from user where _id=?",
                new Object[] { String.valueOf(id) });
    }

    public String findAll() {
        Cursor cursor = db.rawQuery("select *from user", null);
        // 参数1:查询的sql语句
        // 参数2:查询的条件
        // cursor.moveToFirst();//移动第一行
        // cursor.moveToLast();//移动到最后一行
        // cursor.moveToPrevious();//移动到前一行
        // cursor.moveToPosition(position);//移动到指定的行
        // cursor.moveToNext();//移动到下一行
        // 创建一个容器
        StringBuffer sb = new StringBuffer();
        while (cursor.moveToNext()) {
            String name = cursor.getString(cursor.getColumnIndex("name"));
            String phone = cursor.getString(cursor.getColumnIndex("phone"));
            sb.append("姓名:" + name + "        电话:" + phone + "\n");
        }
        return sb.toString();
    }

    public String findConditon(int id) {
        Cursor cursor = db.rawQuery("select * from user where _id=?",
                new String[] { String.valueOf(id) });
        String string = "";
        while (cursor.moveToNext()) {
            String name = cursor.getString(cursor.getColumnIndex("name"));
            String phone = cursor.getString(cursor.getColumnIndex("phone"));
            string = "姓名:" + name + "    电话:" + phone + "\n";
        }
        return string;
    }

}


原创粉丝点击