たぼさんの部屋

いちょぼとのんびり

T106 DbConnectionクラスを作った

使い方

DbConnection db = new DbConnection(context);
  • insert
db.openAndInsert(sql);
db.close()
  • select
Cursor cursor = db.openAndSelect(sql);
//cursorを使った処理
db.close();
  • カーソルでのデータ処理は
String sql = "";
sql += "select * from t_latlng ;";
Cursor c = db.openAndSelect(sql);
c.moveToFirst();
for (int i = 0; i < c.getCount(); i++) {
	int no = c.getInt(0);
	Double lat = c.getDouble(1);
	Double lng = c.getDouble(2);
	String str = "" + no + "件目:" + "経度=" + lat + ",緯度=" + lng;
	canvas.drawText(str, 10, 150 + 12 * i, paint);
	c.moveToNext();
}

DbConnection.java

package com.efolab.t106;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
/**
 * DbConnection:
 * SQLiteDatabaseに接続するクラス<br/>
 * 内部クラスとしてSQLiteOpenHelperを持つ<br/>
 * コンストラクタ:DbConnection db = new DbConnection(Context context);
 * @author kamogashira
 * @since 2012/12/6
 * @version 1
 */
public class DbConnection{
	private SQLiteDatabase db = null;
	private static DbOpenHelper dbHelper = null;
	private Cursor cursor = null;
	private static final int DBVER = 3;
	private static final String DBNAME = "geo3";
	private static String CREATE_TABLE =
			"create table t_latlng (" +
			"no INTEGER primary key autoincrement" +
			",lat REAL not null " +
			",lng REAL not null" +
			",send_flg integer DEFAULT 0" +
			",del_flg integer DEFAULT 0);";
	public DbConnection(Context context){
		if(dbHelper == null){
			dbHelper = new DbOpenHelper(context , DBNAME , null , DBVER);
		}
	}
	//insert
	/**
	 * @return void
	 * @param String
	 */
	public void openAndInsert(String sql){
		db = dbHelper.getWritableDatabase();
		db.execSQL(sql);
		db.close();
	}
	//select
	/**
	 * 
	 * @param String
	 * @return Cursor
	 */
	public Cursor openAndSelect(String sql){
		db = dbHelper.getReadableDatabase();
		cursor = db.rawQuery(sql, null);
		
		return cursor;
	}
	//close
	/**
	 * カーソルとデータベース接続を閉じる
	 * @param なし
	 * @return void
	 */
	public void close(){
		if(cursor != null){
			cursor.close();
		}
		if(db != null){
			db.close();
		}
	}
	private static class DbOpenHelper extends SQLiteOpenHelper {
		
		public DbOpenHelper(Context context, String name, CursorFactory factory,
				int version) {
			super(context, name, factory, version);

		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			//GeoPoint用のテーブルを生成する
			db.execSQL(CREATE_TABLE);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			//GeoPoint用のテーブルを生成する
			db.execSQL(CREATE_TABLE);
		}
	}
}