日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 综合教程 >内容正文

综合教程

android开发之使用SQLite数据库(db文件)

發布時間:2023/12/19 综合教程 25 生活家
生活随笔 收集整理的這篇文章主要介紹了 android开发之使用SQLite数据库(db文件) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

在開發中,有時須要使用db文件數據庫。所以就須要將其導入項目,再將其使用程序寫入到應用的db文件下使用。

代碼非常easy。能夠拿來直接使用。

要使用須要兩個步驟:

1.創建raw文件。導入db文件。例如以下:

2.代碼

public class DBOpenHelper {
	private final int BUFFER_SIZE = 400000;
	public static final String DB_NAME = "idiom.db"; // 保存的數據庫文件名稱
	public static final String PACKAGE_NAME = "cn.edu.bzu.happy";// 應用的包名
	public static final String DB_PATH = "/data"
			+ Environment.getDataDirectory().getAbsolutePath() +"/"
			+ PACKAGE_NAME+ "/databases"; // 在手機里存放數據庫的位置
	//sdcard的路徑(在android 4.4中不好使,文件成功創建是在手機的)
	//public static final String DB_PATH = Environment.getExternalStorageDirectory().getAbsolutePath()+"/idiom";

	private Context context;
	
	public DBOpenHelper(Context context) {
		this.context = context;
	}


	public SQLiteDatabase openDatabase() {
		try {
			File myDataPath = new File(DB_PATH);
			if (!myDataPath.exists())
			{		
				myDataPath.mkdirs();// 假設沒有這個文件夾,則創建
			}
			String dbfile=myDataPath+"/"+DB_NAME;
			if (!(new File(dbfile).exists())) {// 推斷數據庫文件是否存在,若不存在則運行導入,否則直接打開數據庫
				InputStream is = context.getResources().openRawResource(
						R.raw.idiom); // 欲導入的數據庫
				FileOutputStream fos = new FileOutputStream(dbfile);
				byte[] buffer = new byte[BUFFER_SIZE];
				int count = 0;
				while ((count = is.read(buffer)) > 0) {
					fos.write(buffer, 0, count);
				}
				fos.close();
				is.close();
			}
			SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile,
					null);
			return db;
		} catch (FileNotFoundException e) {
			Log.e("Database", "File not found");
			e.printStackTrace();
		} catch (IOException e) {
			Log.e("Database", "IO exception");
			e.printStackTrace();
		}
		return null;
	}


}

使用:

public class TestDao {
	private DBOpenHelper dbHelper;

	public TestDao (Context context) {
		dbHelper = new DBOpenHelper(context);
	}

	public List<Test> getAllTests() {
		List<Test> animals = new ArrayList<Test>();
		SQLiteDatabase sqLiteDatabase = dbHelper.openDatabase();
		Cursor cursor = sqLiteDatabase.rawQuery("select * from test", null);
		While(cursor.moveToNext()){
		//獲取你的數據
		}
	}
}

TestDao  test = new TestDao();

test.getAllTests();

總結

以上是生活随笔為你收集整理的android开发之使用SQLite数据库(db文件)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。