Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android--數據庫操作輔助類:SQLiteOpenHelper

Android--數據庫操作輔助類:SQLiteOpenHelper

編輯:關於Android編程

1.MyDatabaseHelper.java代碼如下:

package org.lxh.demo;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class MyDatabaseHelper extends SQLiteOpenHelper {
	private static final String DATABASENAME = "test.db";
	private static final int DATABASEVERSION = 1;
	private static final String TABLENAME = "mytab";

	public MyDatabaseHelper(Context context) {
		super(context, DATABASENAME, null, DATABASEVERSION);

	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		/*
		 * String sql="CREATE TABLE"+TABLENAME+"("+
		 * "id    INTEGER    PRIMARY KEY,"+ "name   VARCHAR(50)  NOT NULL,"+
		 * "birthday   DATE   NOT NULL)";
		 */
		String sql = "CREATE TABLE " + TABLENAME
				+ "("
				+ "id		INTEGER			PRIMARY KEY ," // 在SQLite中設置為Integer、PRIMARY
												// KEY則ID自動增長
				+ "name 	VARCHAR(50) 	NOT NULL ," + "birthday DATE NOT 		NULL"
				+ ")";
		db.execSQL(sql); // 執行SQL

	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		String sql = "DROP TABLE IF EXISTS" + TABLENAME;
		db.execSQL(sql);
		this.onCreate(db);

	}

}
2.Hello.java代碼如下:

package org.lxh.demo;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Hello extends Activity {
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState); // 生命周期方法
		super.setContentView(R.layout.main); // 設置要使用的布局管理器
		SQLiteOpenHelper helper=new MyDatabaseHelper(this);
		helper.getWritableDatabase();

	}
}

運行後如下:



  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved