????1. ????????????????AndroidManifest.xml?????????????д???
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
package com.bwf.a11_sql_03;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteCantOpenDatabaseException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends Activity {
// ?????????????·??
String dbPath = "/storage/sdcard/DB/person.db";
Cursor cursor;
String sql = "";
SQLiteDatabase db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//openOrCreateDB();
//db_openDB();
//db_openOrCreateDb();
}
/**
* ???SQLiteDatabase??openOrCreateDatabase??????????????????
* */
private void db_openOrCreateDb() {
/**
* @param String name            ???????·??
* @param CursorFactory factory    ?α???
* */
db = SQLiteDatabase.openOrCreateDatabase(dbPath?? null);
hasTableToSelect();
}
/**
* ???SQLiteDatabase??openDatabase???????????
* */
private void db_openDB() {
try{
// ???SQLiteDataBase???????????????
// ??????????????????SQLiteCantOpenDatabaseException
/**
* @param String name            ???????·??
* @param CursorFactory factory    ?α???
* @param int mode                ???
* */
db = SQLiteDatabase.openDatabase(dbPath?? null?? MODE_PRIVATE);
sql = "select * from person";
cursor = db.rawQuery(sql?? null);
showData(cursor);
} catch(SQLiteCantOpenDatabaseException e){
// ??????
}
}
/**
* ???ContextWrapper?е?openOrCreateDatabase??????????????????
* */
private void openOrCreateDB() {
// ??????????????ContextWrapper????????????openOrCreateDatabase
/**
* @param String name            ???????·??
* @param int mode                ???
* @param CursorFactory factory    ?α???
* */
db = openOrCreateDatabase(dbPath?? MODE_PRIVATE?? null);
hasTableToSelect();
}
/**
* ????????????????????????
* */
private void hasTableToSelect() {
try{
sql = "select * from person";
cursor = db.rawQuery(sql?? null);
} catch(SQLiteException s){
sql = "create table if not exists person(name varchar(10)?? age integer)";
db.execSQL(sql);
sql = "insert into person values ('????'??22)";
db.execSQL(sql);
sql = "insert into person values ('????'??21)";
db.execSQL(sql);
sql = "select * from person";
cursor = db.rawQuery(sql?? null);
}
showData(cursor);
}
/**
* ?????
* */
private void showData(Cursor cursor) {
while(cursor.moveToNext()){
String name = cursor.getString(cursor.getColumnIndex("name"));
int age = cursor.getInt(cursor.getColumnIndex("age"));
Log.d("fanhy"?? "name:"+name+"??age:"+age);
}
}
}