android数据库操作

SQLiteOPenHelper类

public class BookDao extends SQLiteOpenHelper {
	/**
	 * 数据库名字
	 */
	public static String DB_NAME = "lib.db";
	/**
	 * 表名
	 */
	public static String TAB_NAME = "lib_book_tab";
	/**
	 * 版本号
	 */
	public static int DB_VERSION = 1;

	/**
	 * bookbean
	 */
	// private ArrayList<BookBean> booklist = new ArrayList<BookBean>();

	public BookDao(Context context) {
		super(context, DB_NAME, null, DB_VERSION);
	}

	/**
	 * @description 创建数据库
	 * @param context
	 *            内容
	 * @param name
	 *            数据库名字
	 * @param factory
	 *            CursorFactory指定在执行查询时获得一个游标实例的工厂类,设置为null,代表使用系统默认的工厂类
	 * @param version
	 *            版本号
	 */

	public BookDao(Context context, String name, CursorFactory factory,
			int version) {
		super(context, DB_NAME, factory, DB_VERSION);
		// TODO Auto-generated constructor stub
	}

	/**
	 * @description 建表
	 */
	@Override
	public void onCreate(SQLiteDatabase db) {
		System.out.println("----------------->");
		String sql = "create table " + TAB_NAME + " (" + BookBean.FILED_ID
				+ " integer primary key autoincrement, "
				+ BookBean.FILED_BOOKNAME + " varchar(20), "
				+ BookBean.FILED_WRITER + " text, " + BookBean.FILED_PRESS
				+ " varchar(20), " + BookBean.FILED_PRICE + " long, "
				+ " bookno " + " varchar(20)" + ")";
		System.out.println("sql建表--->" + sql);
		db.execSQL(sql);
	}

	/**
	 * @description 更新数据库
	 */
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		Log.i("tag", "onUpgrade");
		String sql = "drop table if exist " + TAB_NAME;
		db.execSQL(sql);
		onCreate(db);
	}

	/**
	 * @description 插入
	 */
	public void insert() {
		// SQLiteDatabase db=DB_NAME;
	}
}

查找和添加

public class Test extends Activity {
	// protected void onCreate(android.os.Bundle savedInstanceState) {
	// };
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		BookDao book = new BookDao(this);

		SQLiteDatabase db = book.getWritableDatabase();

		try {

			// 增加
			// String sql = "insert into " + BookDao.TAB_NAME
			// + "(bookname,writer,press,price,bookno) values(?,?,?,?,?)";
			// db.execSQL(sql, new Object[] { "a", "a", "a", 1, "a" });

			// 查找
			Cursor cursor = db.rawQuery("select * from " + BookDao.TAB_NAME,
					null);
			while (cursor.moveToNext()) {
				System.out.println(cursor.getString(0));
				System.out.println(cursor.getString(1));
				System.out.println(cursor.getString(2));
				System.out.println(cursor.getString(3));
				System.out.println(cursor.getString(4));
			}

			System.out.println("success");
		} catch (Exception e) {
			System.out.println("fail");
			e.printStackTrace();
		}
	}
}


你可能感兴趣的:(android数据库操作)