标签:
public class DatabaseHelper extends SQLiteOpenHelper { //类没有实例化,是不能用作父类构造器的参数,必须声明为静态 private static final String name = "itcast"; //数据库名称 private static final int version = 1; //数据库版本 public DatabaseHelper(Context context) { //第三个参数CursorFactory指定在执行查询时获得一个游标实例的工厂类,设置为null,代表使用系统默认的工厂类 super(context, name, null, version); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE IF NOT EXISTS person (personid integer primary key autoincrement, name varchar(20), age INTEGER)"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL(" ALTER TABLE person ADD phone VARCHAR(12) NULL "); //往表中增加一列 // DROP TABLE IF EXISTS person 删除表 } }
Cursor cursor = db.rawQuery(“select * from person”, null); while (cursor.moveToNext()) { int personid = cursor.getInt(0); //获取第一列的值,第一列的索引从0开始 String name = cursor.getString(1);//获取第二列的值 int age = cursor.getInt(2);//获取第三列的值 } cursor.close();
SQLiteDatabase db = databaseHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("name", "测试数据"); values.put("age", 4); long rowid = db.insert(“person”, null, values);//返回新添记录的行号,与主键id无关
SQLiteDatabase db = databaseHelper.getWritableDatabase(); db.delete("person", "personid<?", new String[]{"2"}); db.close();
SQLiteDatabase db = databaseHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(“name”, “测试数据”);//key为字段名,value为值 db.update("person", values, "personid=?", new String[]{"1"}); db.close();
SQLiteDatabase db = databaseHelper.getWritableDatabase(); Cursor cursor = db.query("person", new String[]{"personid,name,age"}, "name like ?", new String[]{"%传智%"}, null, null, "personid desc", "1,2"); while (cursor.moveToNext()) { int personid = cursor.getInt(0); //获取第一列的值,第一列的索引从0开始 String name = cursor.getString(1);//获取第二列的值 int age = cursor.getInt(2);//获取第三列的值 } cursor.close(); db.close();
package com.zyq.db; import android.app.Activity; import android.os.Bundle; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } }
package com.zyq.db; import java.util.List; import android.test.AndroidTestCase; import android.util.Log; import com.zyq.service.DBOpenHelper; import com.zyq.service.PersonService; import com.zyq.voo.Person; /** * 测试方法 通过Junit 单元测试 * 1.>实例化测试类 * 2.>把与应用有关的上下文信息传入到测试类实例 * 3.>运行测试方法 * @author Administrator * */ public class PersonServiceTest extends AndroidTestCase { private final static String TAG="PersonServiceTest"; /** * 测试创建数据库 * @throws Throwable */ public void testCreateDB() throws Throwable { DBOpenHelper dbOpenHelper=new DBOpenHelper(this.getContext()); dbOpenHelper.getReadableDatabase(); //Create and/or open a database. } /** * 测试新增一条记录 * @throws Throwable */ public void testSave() throws Throwable { PersonService personService=new PersonService(this.getContext()); personService.save(new Person("zhangsan","1360215320")); personService.save(new Person("lisi","1123")); personService.save(new Person("lili","232")); personService.save(new Person("wangda","123123")); personService.save(new Person("laozhu","234532")); } /** * 查找一条记录 * @throws Throwable */ public void testFind() throws Throwable { PersonService personService=new PersonService(this.getContext()); Person person=personService.find(1); Log.i(TAG,person.toString()); } /** * 测试更新一条记录 * @throws Throwable */ public void testUpdate() throws Throwable { PersonService personService=new PersonService(this.getContext()); Person person=personService.find(1); person.setName("lisi"); personService.update(person); } /** * 测试得到所有记录数 * @throws Throwable */ public void testGetCount() throws Throwable { PersonService personService=new PersonService(this.getContext()); Log.i(TAG, personService.getCount()+"********"); } /** * 测试分页 * @throws Throwable */ public void testScroll() throws Throwable { PersonService personService=new PersonService(this.getContext()); List<Person> persons=personService.getScrollData(3, 3); for(Person person:persons) { Log.i(TAG, person.toString()); } } /** * 测试删除一条记录 * @throws Throwable */ public void testDelete() throws Throwable { PersonService personService=new PersonService(this.getContext()); personService.delete(5); } } 复制代码 代码如下: package com.zyq.service; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class DBOpenHelper extends SQLiteOpenHelper { /** * 如果想额外的增加一个字段(需求) * 可以把版本号更改掉 但必须 >=1 * 更改版本号之后 会根据版本号判断是不是上次创建的时候 (目前的版本号和传入的版本号是否一致 ) * 如果不是会执行 onUpgrade() 方法 * @param context */ public DBOpenHelper(Context context) { super(context, "zyq.db", null, 2); } /** * 在数据库创建的时候第一个调用的方法 * 适合创建表结构 */ @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE person (personid integer primary key autoincrement, name varchar(20))");//创建表 } /** * 更新表结构 在数据库版本号发生改变的时候调用 * 应用升级 */ @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("ALTER TABLE person ADD phone VARCHAR(12) NULL "); //往表中增加一列 } } 复制代码 代码如下: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.zyq.db" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <uses-library android:name="android.test.runner" /> <activity android:name=".MainActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <uses-sdk android:minSdkVersion="8" /> <instrumentation android:name="android.test.InstrumentationTestRunner" android:targetPackage="com.zyq.db" android:label="Tests for My App" /> </manifest> 复制代码 代码如下: package com.zyq.service; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.zyq.voo.Person; public class PersonService { private DBOpenHelper helper; public PersonService(Context context) { helper=new DBOpenHelper(context); } /** * 新增一条记录 * @param person */ public void save(Person person) { SQLiteDatabase db=helper.getWritableDatabase();//Create and/or open a database that will be used for reading and writing db.execSQL("INSERT INTO person(name,phone) values(?,?)",new Object[]{person.getName().trim(),person.getPhone().trim()});//使用占位符进行转译 // db.close(); 不关数据库连接 。可以提高性能 因为创建数据库的时候的操作模式是私有的。 //代表此数据库,只能被本应用所访问 单用户的,可以维持长久的链接 } /** * 更新某一条记录 * @param person */ public void update(Person person) { SQLiteDatabase db=helper.getWritableDatabase(); db.execSQL("update person set phone=?,name=? where personid=?", new Object[]{person.getPhone().trim(),person.getName().trim(),person.getId()}); } /** * 根据ID查询某条记录 * @param id * @return */ public Person find(Integer id) { SQLiteDatabase db=helper.getReadableDatabase(); Cursor cursor=db.rawQuery("select * from person where personid=?", new String[]{id.toString()});//Cursor 游标和 ResultSet 很像 if(cursor.moveToFirst())//Move the cursor to the first row. This method will return false if the cursor is empty. { int personid=cursor.getInt(cursor.getColumnIndex("personid")); String name=cursor.getString(cursor.getColumnIndex("name")); String phone=cursor.getString(cursor.getColumnIndex("phone")); return new Person(personid,name,phone); } return null; } /** * 删除某一条记录 * @param id */ public void delete(Integer id) { SQLiteDatabase db=helper.getWritableDatabase(); db.execSQL("delete from person where personid=?", new Object[]{id}); } /** * 得到记录数 * @return */ public long getCount() { SQLiteDatabase db=helper.getReadableDatabase(); Cursor cursor=db.rawQuery("select count(*) from person", null); cursor.moveToFirst(); return cursor.getLong(0); } /** * 分页查询方法 SQL语句跟MySQL的语法一样 * @return */ public List<Person> getScrollData(int offset,int maxResult) { List<Person> persons=new ArrayList<Person>(); SQLiteDatabase db=helper.getReadableDatabase(); Cursor cursor=db.rawQuery("select * from person limit ?,?", new String[]{String.valueOf(offset),String.valueOf(maxResult)}); while (cursor.moveToNext()) { int personid=cursor.getInt(cursor.getColumnIndex("personid")); String name=cursor.getString(cursor.getColumnIndex("name")); String phone=cursor.getString(cursor.getColumnIndex("phone")); persons.add(new Person(personid,name,phone)); } return persons; } } 复制代码 代码如下: package com.zyq.voo; public class Person { private Integer id; private String name; private String phone; public Person(int personid, String name, String phone) { this.id=personid; this.name=name; this.phone=phone; } public Person(String name, String phone) { this.name = name; this.phone = phone; } public String toString() { return "Person [id=" + id + ", name=" + name + ", phone=" + phone + "]"; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } }
标签:
原文地址:http://www.cnblogs.com/xiaoxiaoshen/p/5167520.html