MainActivity.class
package com.superxingyun.sqlite_2;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
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("student.db", MODE_PRIVATE, null);
db.execSQL("create table if not exists student (_id integer primary key autoincrement," +
"name text not null, sex text not null, age integer not null)");
ContentValues values = new ContentValues();
values.put("name", "劫1");
values.put("sex", "男");
values.put("age", 10);
//insert返回值为long,为id,需要可以返回
long rowId = db.insert("student", null, values);
values.put("name", "劫2");
values.put("sex", "男");
values.put("age", 20);
db.insert("student", null, values);
values.clear();
values.put("name", "劫3");
values.put("sex", "男");
values.put("age", 30);
db.insert("student", null, values);
values.clear();
values.put("name", "劫4");
values.put("sex", "男");
values.put("age", 40);
db.insert("student", null, values);
/**
* 数据库操作,增删查改
*/
//update数据前也要clear,将id>3的性别改为 女
values.clear();
values.put("sex", "女");
db.update("student",values, "_id>?", new String[]{"3"});//修改id大于3的数据
db.delete("student", "name like ?", new String[]{"%1%"});//删除名字中带有1的数据
//查询结果为游标对象,需要判断
Cursor c = db.query("student", null, "_id > ?", new String[]{"0"}, null, null, "age");
if (c != null){
String columns [] = c.getColumnNames();
while (c.moveToNext()){
for (String columnsName : columns){
Log.i("info", c.getString(c.getColumnIndex(columnsName)));
}
}
c.close();
}
db.close();
}
}
对数据库操作注意主键 “_ “,