android怎么连接sqlite数据库?

SQLite数据库
首先先建立SQLiteOpenHelper()的子类实现SQLiteOpenHelper中的OnCreate()方法和构造方法。 this class takes care of opening the database if it exists, creating it if it does not, and upgrading it as necessary. SQLiteOpenHelper()主要是提供数据库的对象,其中的getWriteableDatabase public class PersonSQLiteOpenHelper extends SQLiteOpenHelper
{
public PersonSQLiteOpenHelper(Context context)
{
super(context, "person.db", null, 1);
} /**
* 第一次被创建的时候调用的方法
*/
@Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL("create table person(id primary key autoincrement,name varchar(20),number varchar(20)");
} @Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2)
{ } } 有了SQLiteOpenHelper的子类后,就可建立其引用hrelper,用引用获得数据库db=helper.getWritableDataBase();
Db.execSQL(“select * from table”);
建立与数据库操作相关的类(选择)
public class PersonDao
{
private PersonSQLiteOpenHelper helper; public PersonDao(Context context)
{
helper = new PersonSQLiteOpenHelper(context);
}
/**
*
* @param name
* @param number
*/
public void add(String name, String number)
{
SQLiteDatabase db = helper.getWritableDatabase();
db.execSQL("insert into person(name,number) values(?,?)", new Object[] {
name, number });
db.close();
} /**
*
* @param name
* @return
*/
public boolean find(String name)
{
SQLiteDatabase db = helper.getReadableDatabase();
Cursor cursor = db.rawQuery("select *from person where name=?",
new String[] { name });
boolean result = cursor.moveToNext();
cursor.close();
db.close();
return result;
} /**
*
* @param name
* @param number
*/
public void update(String name, String number)
{
SQLiteDatabase db = helper.getWritableDatabase();
db.execSQL("update person set number=? where name=?", new Object[] {
number, name });
db.close();
} /**
*
* @param name
*/
public void delete(String name)
{
SQLiteDatabase db = helper.getWritableDatabase();
db.execSQL("delete from person where name=?", new Object[] { name });
db.close();
}
/**
*
* @return
*/
public List<Person> findAll()
{
SQLiteDatabase db = helper.getReadableDatabase();
Cursor cursor = db.rawQuery("select *from person", null);
ArrayList<Person> list = new ArrayList<Person>();
while (cursor.moveToNext())
{
int id = cursor.getInt(cursor.getColumnIndex("id"));
String name = cursor.getString(cursor.getColumnIndex("name"));
String number = cursor
.getString(cursor.getColumnIndex("number"));
Person person = new Person(id, name, number);
list.add(person);
}
return list;
}
} 事物
//开启事物
db.beginTransaction();
try
{
//标记事物执行成功
db.setTransactionSuccessful();
} finally
{
db.endTransaction();
}
上一篇:[Cocos2D-x For WP8]Box2D物理引擎


下一篇:Centos永久路由添加教程