使用sqlite第一步需要建一个类继承与sqliteOpenHelper
package com.example.databasetest; import android.content.Context; import android.database.sqlite.sqliteDatabase; import android.database.sqlite.sqliteDatabase.CursorFactory; import android.database.sqlite.sqliteOpenHelper; import android.widget.Button; import android.widget.Toast; public class DataBaseHelper extends sqliteOpenHelper{ Context mcontext; //建表语句 public static final String CREATE_BOOK = "create table Book (" +"id integer primary key autoincrement," +"name text)"; public DataBaseHelper(Context context,String name,CursorFactory factory,int version) { super(context,name,factory,version); mcontext = context; // TODO Auto-generated constructor stub } @Override public void onCreate(sqliteDatabase arg0) { // TODO Auto-generated method stub //创建表 arg0.execsql(CREATE_BOOK); Toast.makeText(mcontext,"Create Success",Toast.LENGTH_SHORT).show(); } //此方法主要用于升级数据库 @Override public void onUpgrade(sqliteDatabase arg0,int arg1,int arg2) { // TODO Auto-generated method stub } }
主活动代码:
package com.example.databasetest; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MainActivity extends Activity { Button button; DataBaseHelper dataBaseHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); dataBaseHelper = new DataBaseHelper(this,"book.db",null,1); button = (Button)findViewById(R.id.create_button); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub // dataBaseHelper.getReadableDatabase(); } }); } @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; } }
db = dataBaseHelper.getReadableDatabase(); cv = new ContentValues(); cv.put("name","name"); db.insert("Book",cv);
更新数据:
db = dataBaseHelper.getReadableDatabase(); cv = new ContentValues(); cv.put("price","10"); //更新名称为name_1这些数据的price值为10 db.update("Book",cv,"name = ?",new String[]{"name_1"});
删除数据:
//删除price大于500的这些数据 db.delete("tableName","price > ?",new String[]{"500"});
查询数据:
db = dataBaseHelper.getReadableDatabase(); // 返回的数据都在Cursor里面, Cursor cursor = db.query("Book",null); // 下面进行读取 //把光标移向第一行 if (cursor.moveToFirst()) { do { String name = cursor.getString(cursor .getColumnIndex("name")); int price = cursor.getInt(cursor .getColumnIndex("price")); //把光标移向下一行 } while (cursor.moveToNext()); }
查看手机数据的方法:
打开安卓SDK目录下的platform-tools目录,将它的路径配置到系统变量里面去如图:
然后就可以在doc窗口下进行操作了,步骤如下:
(1)在doc窗口输入 cd data/data/程序的包名/databases/
(2)接着输入 ls 即可查看该目录下的内容了,其中后缀名为:db-journal的则是为了让数据库能够支持事务而产生的临时日志文件。
(3)接着输入 sqlite3,后面加上数据库名如:name.db,这样数据库就被打开了,就可以对这个数据库进行操作了
(4)查看有哪些表则输入 .table即可,使用 .schema来查看它们的建表语句啦