SQLite数据库基本操作

SQLite数据库的建立

public class MyHelper extends SQLiteOpenHelper{
	public MyHelper(Context context){
		super(context,"itcast.db",null,2);//2 为数据库版本
	}
	public void onCreate(SQLiteDatabase db){
		db.execSQl("CREATE TABLE information(_id INTEGER PRIMARY KEY AUTOINCREMENT,name VARCHAR(20),price INTEGER)");
	}
	public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion){
	//版本号增加时调用
	}
}

数据库的基本操作

  • 添加数据
public void insert(String name,String price){
	MyHelper helper=new MyHelper(MainActivity.this);
	SQliteDatabase db=helper.getWritableDababase();
	//获取可读写SQLiteData对象
	ContentValues values =new ContentValues();
	values.put("name",name);//第一个为表中列名,第二个为列对应的值
	values.put("price",price);
	//创建ContentValues对象并将数据添加到ContentValues对象在
	long id=db.insert("information",null,values);
	//调用insert()方法将函数添加到数据库中,插入information表中,//null为如果发现将要插入的行为空行,将列名值设为null
	db.close();//关闭数据库
} 
  • 删除数据
public int delete(long id){
	SQliteDatabase db=helper.getWritableDatabase();
	int number=db.delete("information","_id=?",new String[]{id+""});
	//调用delete()方法删除数据库中指定数据 information为表名称 _id表中列名 String数组则为列名中删除的数据
	//返回的number是删除数据的行数,不成功为0
	db.close();
	return number;
  • 修改数据库
public int updata(String name,String price){
	SQLiteDatavase db=helper.getWritableDatabase();
	ContentValues values=new ContentValues();
	values.put("price",price);
	//创建ContenValues对象将修改的数据添加到ContenValues对象中
	int number=db.update("information",values,"name=?",new Strin[]{name});
	//调用updata()方法修改数据,information表名称 values修改的数据 name=?修改数据的查找条件 String查找条件的参数
	//在information中找到列名name值为参数String中name时,修改列price值为price
	//number为更新数据的行数,不成功0
	db.close();
	return number;
}
  • 查询数据
public void find(int id){
	MyHelper helper=new MyHelper(MainActivity.this);
	SQLiteDatabase db=helper.getReadableDatabase();
	Cursor cursor=db.query("information",null,"_id=?",new String[]{id+""},null,null,null);
	//调用query()方法查询数据库中的数据,返回一个Cursor对象
	//第二个null为查询的列名,_id查询条件,String对应查询条件的条件值,
	//第五null分组方式,第六null定义组的一个过滤器,第7null为排序方式
	if(cursor.getCount()!=0){ //数据条总数
		while(cursor.moveToNext(){  //移动游标指向下一行数据
			String _id=cursor.getString(cursor.getColumnIndex("_id"));
			String name=cursor.getString(cursor.getColumnIndex("name"));
		}		
	}
	cursor.close();
	db.close();
{
  • 使用Sql语句进行数据库操作
//增加一条数据
db.execSQL("insert into information(name,price) values(?,?)",new Object[]{name,price});
//删除一条数据
db.execSQL("delete from information where _id=1");
//修改一条数据
db.execSQL("updata information set name=? where price=?",new Object[]{name,price});
//执行查询的SQL语句
Cursor cursor=db.rawQuery("select * from information where name=?",new String[]{name});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值