sqlite 使用方法

前端之家收集整理的这篇文章主要介绍了sqlite 使用方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

是一个嵌入式数据库,占资源少,支持关系型数据库。Android系统采用了此数据库,有关操作的类有sqliteDatabase 和接口sqliteOpenHelper。建立应用程序与sqlite的连接,以及对其库中数据操作关键代码如下:

1、//实现接口sqliteOpenHelper的类 ,其中的构造函数

public DatabaseHelper(Context context,String name,CursorFactory factory,
int version) {
super(context,name,factory,version);
// TODO Auto-generated constructor stub
}

2、//重写onCreate函数

public void onCreate(sqliteDatabase db) {
// TODO Auto-generated method stub
db.execsql("create table user(id int,name varchar(20))");

}

3、创建数据库的关键代码

class CreateOnClick implements OnClickListener
{

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
DatabaseHelper dbHelper = new DatabaseHelper(sqliteActivity.this,"test_db");
sqliteDatabase db = dbHelper.getReadableDatabase();
}

}

4、更新数据库的关键代码

class UpdateOnClick implements OnClickListener
{

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
DatabaseHelper dbHelper = new DatabaseHelper(sqliteActivity.this,"test_db",null,2);
sqliteDatabase db = dbHelper.getReadableDatabase();
}

}

5、插入数据表数据的关键代码

class InsertOnClick implements OnClickListener
{

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
ContentValues values = new ContentValues();
values.put("id",1);
values.put("name","zhao");
DatabaseHelper dbHelper = new DatabaseHelper(sqliteActivity.this,"test_db");
sqliteDatabase db = dbHelper.getWritableDatabase();
db.insert("user",values);
}

6、删除数据表数据的关键代码

class DeleteOnClick implements OnClickListener
{

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
DatabaseHelper dbHelper = new DatabaseHelper(sqliteActivity.this,"test_db");
sqliteDatabase db = dbHelper.getWritableDatabase();
db.delete("user","name='zhao'",null);
System.out.println("record delete");
}

}

7、更新数据表数据的关键代码

class UpdatingOnClick implements OnClickListener
{

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
ContentValues values = new ContentValues();
values.put("name","zhangsan");
DatabaseHelper dbHelper = new DatabaseHelper(sqliteActivity.this,"test_db");
sqliteDatabase db = dbHelper.getWritableDatabase();
db.update("user",values,"id=?",new String[]{"1"});
}

}

8、查询数据表中数据的关键代码

class QueryOnClick implements OnClickListener { @Override public void onClick(View v) { // TODO Auto-generated method stub DatabaseHelper dbHelper = new DatabaseHelper(sqliteActivity.this,"test_db"); sqliteDatabase db = dbHelper.getWritableDatabase(); Cursor cursor = db.query ("user",new String[]{"id","name"},new String[]{"1"},null); while(cursor.moveToNext()) { String name = cursor.getString(cursor.getColumnIndex("name")); System.out.print("query----->" + name); } } }

原文链接:https://www.f2er.com/sqlite/202693.html

猜你在找的Sqlite相关文章