创建Sqlite数据库(二)
先创建一个数据库表,然后在主activity中执行删除更新操作
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Mysqlite mysqlite = new Mysqlite(this); SQLiteDatabase sqLiteDatabase = mysqlite.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put("id", 0); contentValues.put("name", "张三"); sqLiteDatabase.insert("student", null, contentValues); System.out.println("插入数据"); Cursor cursor = sqLiteDatabase.query("student", new String[]{"id", "name"}, "id=?", new String[]{"0"}, null, null, null); while (cursor.moveToNext()) { String id = cursor.getString(cursor.getColumnIndex("id")); String name = cursor.getString(cursor.getColumnIndex("name")); System.out.println(id + " " + name); } ContentValues contentValues1 = new ContentValues(); contentValues1.put("name", "李四"); sqLiteDatabase.update("student", contentValues1, "id=?", new String[]{"0"});//?是占位符,后面String //数组的元素0填补前面的占位符?,也就是id=0,whereClause(where字句)只是一个限制条件 System.out.println("更新数据"); sqLiteDatabase.delete("student", "id=?", new String[]{"0"}); System.out.println("删除数据"); deleteDatabase("student"); System.out.println("删除数据库"); sqLiteDatabase.close(); } }
上面是主Activity,不要重复创建sqliteDatabase,不然内部无法同步
public class Mysqlite extends SQLiteOpenHelper { SQLiteDatabase readableDatabase; public Mysqlite(Context context) { super(context, "student", null, 2); readableDatabase = getWritableDatabase();//创建数据库不需要什么权限,但是这行代码一定要写 } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("create table student (id integer,name varchar)"); System.out.println("创建"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }
上面是创建数据库//重要的事情说三遍