SQLite增删改查的基本使用语法:
打印的log如下:
package com.example.sqlitedemo;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SQLiteDatabase db = openOrCreateDatabase("stu.db",MODE_PRIVATE,null);
db.execSQL("create table if not exists stutb(_id integer primary key autoincrement,name text not null,sex text not null,age integer not null)");
ContentValues cv = new ContentValues();
cv.put("name","张三");
cv.put("sex","男");
cv.put("age",19);
long rowId = db.insert("stutb",null,cv);
cv.clear();
cv.put("name","张三11");
cv.put("sex","男");
cv.put("age",22);
db.insert("stutb",null,cv);
cv.clear();
cv.put("name","张三22");
cv.put("sex","男");
cv.put("age",33);
db.insert("stutb",null,cv);
cv.clear();
cv.put("name","张三33");
cv.put("sex","男");
cv.put("age",44);
db.insert("stutb",null,cv);
cv.clear();
cv.put("name","张三44");
cv.put("sex","男");
cv.put("age",55);
db.insert("stutb",null,cv);
cv.clear();
cv.put("sex","女");
db.update("stutb",cv,"_id>?",new String[]{"3"});//将ID大于三的性别全部改成女
db.delete("stutb","name like ?",new String[]{"%11%"});//条件删除名字中带有“11”的学生
Cursor cursor =db.query("stutb",null,"_id>?",new String[]{"0"},null,null,null);
if (cursor!=null){
String [] columns = cursor.getColumnNames();
while (cursor.moveToNext()){
for (String columnName:columns){
Log.d("info",cursor.getString(cursor.getColumnIndex(columnName)));
}
}
cursor.close();
}
db.close();
}
}