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);
}
}
}