數(shù)據(jù)庫(kù)操作
正則表達(dá)式
IO流
數(shù)據(jù)庫(kù)拷貝
- 為什么要拷貝數(shù)據(jù)庫(kù)觅玻?
我們將數(shù)據(jù)庫(kù)儲(chǔ)存在assets文件夾中刚陡,而數(shù)據(jù)庫(kù)的操作必須要將數(shù)據(jù)庫(kù)放在PATH="data/data/com.phonesafe/files/adress.db"路徑下,所以在初始化界面就需要操作數(shù)據(jù)庫(kù)的拷貝
- 獲取PATH的路徑(getFilesDir()),
- 判斷是否已經(jīng)存在該文件
- 使用IO復(fù)制文件
<pre>
public void CopyDB(String dbname){
File file=new File(getFilesDir(),dbname);
if (file.exists()){
return ;
}
try {
InputStream inputStream=getAssets().open(dbname);
FileOutputStream fileOutputStream=new FileOutputStream(file);
int len=0;
byte[] buffer=new byte[1024];
while ((len=inputStream.read(buffer))!=-1){
fileOutputStream.write(buffer,0,len);
}
} catch (IOException e) {
e.printStackTrace();
}
}
</pre>
數(shù)據(jù)庫(kù)操作
獲取被操作的數(shù)據(jù)庫(kù)對(duì)象
得到查詢數(shù)據(jù)結(jié)果的對(duì)象Curcor
-
通過(guò)Curcor對(duì)象拿到查詢結(jié)果
<pre>
public class AddressDao {
public static final String PATH="data/data/com.phonesafe/files/address.db";
private static String address="未知號(hào)碼";
public static String getAdress(String number){
//獲取數(shù)據(jù)庫(kù)對(duì)象
SQLiteDatabase database=SQLiteDatabase.openDatabase(PATH, null, SQLiteDatabase.OPEN_READONLY);
//手機(jī)號(hào)碼特點(diǎn) 1+(3,4,5,6,7,8)+(9位數(shù)字)
if (number.matches("^1[3-8]\d{9}$")){
Cursor cursor = database.rawQuery("select location from data2 where id=(select outkey from data1 where id=?)",
new String[]{number.substring(0, 7)});
if (cursor.moveToNext()){
address=cursor.getString(cursor.getColumnIndex("location"));
}
}else if (number.matches("^\d+$")){ //匹配數(shù)字
switch (number.length()){
case 3:
address="報(bào)警電話";
break;
case 4:
address="模擬器";
break;
case 5:
address="客服電話";
break;
case 7:case 8:
address="本地號(hào)碼";
break;default: //01088888888,可能是長(zhǎng)途電話 if (number.startsWith("0")&&number.length()>10){ Cursor cursor = database.rawQuery("select location from data2 where area=?", new String[]{number.substring(1, 4)}); if (cursor.moveToNext()){ address=cursor.getString(cursor.getColumnIndex("location")); }else { cursor.close(); cursor=database.rawQuery("select location from data2 where area=?", new String[]{number.substring(1, 3)}); if (cursor.moveToNext()) { address = cursor.getString(cursor.getColumnIndex("location")); } cursor.close(); } } break; } } database.close(); return address;
}
}
}
</pre>
- 首先獲取打開(kāi)數(shù)據(jù)庫(kù)的對(duì)象为牍,這里有三個(gè)參數(shù)馅精,第一個(gè)參數(shù)代表數(shù)據(jù)庫(kù)的地址次慢,第三個(gè)表示數(shù)據(jù)庫(kù)的訪問(wèn)權(quán)限
- 調(diào)用了rawQuery方法旁涤,這個(gè)方法的第一個(gè)參數(shù)是數(shù)據(jù)庫(kù)的Sql語(yǔ)句翔曲,第二參數(shù)代表的是Sql語(yǔ)句占位符的參數(shù),
number.subString(0劈愚,7)表示截取0-7位的數(shù)據(jù)瞳遍,因?yàn)樾枰娫挼那?位查詢。
正則表達(dá)式對(duì)號(hào)碼的判斷
- 標(biāo)準(zhǔn)手機(jī)號(hào)碼判斷
- 標(biāo)準(zhǔn)電話號(hào)碼判斷
- 區(qū)號(hào)判斷
- 手機(jī)號(hào)碼特點(diǎn) 1+(3,4,5,6,7,8)+(9位數(shù)字)判斷是否為手機(jī)號(hào)碼菌羽,
Then
判斷歸屬地掠械。 - 根據(jù)電話號(hào)碼的長(zhǎng)度判斷電話號(hào)碼類型
- 根據(jù)區(qū)號(hào)(前提為電話號(hào)碼,長(zhǎng)度大于8算凿,截取前3或4位)判斷歸屬地