安卓学习笔记——SQLite

2016-12-21 07:42:18来源:CSDN作者:weiwei1994人点击

本段代码摘自施威铭编著《Android APP 开发入门》,已实际运行,没有问题//MainActivity.javapackage com.example.dell.ch15_hellosqlite;import android.content.ContentValues;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.widget.TextView;public class MainActivity extends AppCompatActivity {    static final String db_name = "testDB";    //数据库名称    static final String tb_name = "test";    //数据库表名    SQLiteDatabase db;    //数据库对象    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        //打开或创建数据库        db = openOrCreateDatabase(db_name, Context.MODE_PRIVATE,null);        String createTable = "CREATE TABLE IF NOT EXISTS " +                tb_name +                "(name VARCHAR(32)," +                "phone VARCHAR(16),"+                "email VARCHAR(64))";        db.execSQL(createTable);        Cursor c = db.rawQuery("select * from " + tb_name, null);        if(c.getCount() == 0){    //若无数据,则立即新增两项数据            //调用自定义的addData方法写入两组数据            addData("Flag Publishing Co.","02-23963257","service@flag.com.tw");            addData("PCDIY Magazine","02-23214335","service@pcdiy.com.tw");            c = db.rawQuery("select * from " + tb_name, null);        }        String str = "";        if(c.moveToFirst()){            str = "总共有 "+ c.getCount() + "项数据/n";            str += "------/n";        }        do{            str+="name:"+c.getString(0)+"/n";            str+="phone:"+c.getString(1)+"/n";            str+="email:"+c.getString(2)+"/n";            str+= "------/n";        }while(c.moveToNext());        TextView txv = (TextView)findViewById(R.id.txv);        txv.setText(str + "数据库文件路径:"+db.getPath() + "/n" +                "数据库分页大小:" + db.getPageSize() + "Bytes/n");        db.close();    }    private void addData(String name,String phone,String email){        ContentValues cv = new ContentValues(3);    //创建含3个数据项的对象        cv.put("name",name);        cv.put("phone",phone);        cv.put("email",email);        db.insert(tb_name,null,cv);    //将数据加到数据表    }} 

微信扫一扫

第七城市微信公众平台