Android--数据库操作辅助类:SQLiteOpenHelper

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();

	}
}

运行后如下:

技术分享

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。